[PATCH] D72551: Warn when a string literal is used in a range-based for-loop

Richard Trieu via Phabricator via cfe-commits cfe-commits at lists.llvm.org
Fri Jan 10 18:46:20 PST 2020


rtrieu created this revision.

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")) {}


https://reviews.llvm.org/D72551

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaStmt.cpp
  clang/test/SemaCXX/warn-range-loop-analysis.cpp

-------------- next part --------------
A non-text attachment was scrubbed...
Name: D72551.237448.patch
Type: text/x-patch
Size: 8329 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/cfe-commits/attachments/20200111/738c5a28/attachment.bin>


More information about the cfe-commits mailing list