Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GCC bug in range-based for statement

I seem to have encountered a strange bug in GCC. Consider

for (int i = 5 : {1, 2, 3})
     std::cout << i << ", ";

While this nonsensical code is correctly rejected by Clang, it compiles and executes fine on all recent GCC versions. The strange thing is that no output at all, neither 1, 2, 3 nor 5, 5, 5, is produced.

If we now go further and consider this code

int arr[] {1, 2, 3};
for (int i = 5: arr)
    std::cout << i << ", ";

GCC warns us that the array is not used, which implies that the loop is ignored.

Does this code invoke undefined behavior? Or is it ill-formed, with no diagnostic required? Or is it simply a weird bug?
The standard specifies in [stmt.ranged]/1 that the declaration is substituted into the following line:

for-range-declaration = *__begin;

... and such a declaration would clearly be ill-formed.

Edit: After reporting the bug, Paolo Carlini has fixed it for version 5.0.

like image 266
Columbo Avatar asked Nov 19 '14 23:11

Columbo


1 Answers

Both examples are invalid syntax, which requires a diagnostic.

The syntax for range-based for is in 6.5/1:

iteration-statement:

  • ...
  • for ( for-range-declaration : for-range-initializer ) statement

for-range-declaration:

  • attribute-specifier-seqoptdecl-specifier-seq declarator

which does not allow for an initializer before the colon.

like image 168
aschepler Avatar answered Nov 11 '22 18:11

aschepler