Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 508
StilesCrisis Avatar asked Jan 31 '26 01:01

StilesCrisis


1 Answers

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];
    }
like image 185
mattnewport Avatar answered Feb 02 '26 16:02

mattnewport



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!