Why is the following code illegal?
for (int index=0; index<3; index++)
{
cout << {123, 456, 789}[index];
}
While this works fine:
for (int value : {123, 456, 789})
{
cout << value;
}
Code in IDEOne: http://ideone.com/tElw1w
Why is the following code illegal?
for (int index=0; index<3; index++)
{
cout << {123, 456, 789}[index];
}
While this works fine:
for (int value : {123, 456, 789})
{
cout << value;
}
Code in IDEOne: http://ideone.com/tElw1w
While std::initializer_list
does not provide an operator[]
, it does have overloads for begin()
and end()
which are what the range based for uses. You can in fact index into an initializer_list
like this:
for (int index=0; index<3; index++)
{
cout << begin({123, 456, 789})[index];
}
A braced-init-list like {123, 456, 789}
has no type by itself, and cannot be indexed (nor indeed used with most other operators).
The range-based for
loop has special handling for this case to make it work. (Technically, the special handling is in the auto&&
it uses internally, which deduces a std::initializer_list
from a braced-init-list.)