Page MenuHomePhabricator

Warn when a string literal is used in a range-based for-loop
Needs ReviewPublic

Authored by rtrieu on Jan 10 2020, 6:40 PM.
This revision needs review, but there are no reviewers specified.

Details

Reviewers
None
Summary

String literals used in ranged-based for-loops will actually process the terminating null character as part of the loop, which may be unexpected.

// This runs three times, once for c = 'h', then c = 'i', and finally as c = '\0'
for (char c : "hi")

This patch adds a warning to -Wrange-loop-analysis when this is used. Two ways to silence the warning are proposed, by either handling the null character in the first statement of the loop body or by putting the string literal in parentheses.

// warning
for (char c : "hi") {}

// silence by handling null character
for (char c : "hi") {
  if (c == '\0') {}
}

// silence by parentheses
for (char c : ("hi")) {}

Diff Detail

Event Timeline

rtrieu created this revision.Jan 10 2020, 6:40 PM