Search code examples
c++initializer-listlist-initialization

Trying to understand C++ brace-initialization syntax better


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


Solution

  • 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];
        }