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.
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)
statementfor-range-declaration:
- attribute-specifier-seqoptdecl-specifier-seq declarator
which does not allow for an initializer before the colon.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With