Search code examples
c++c++11for-loopforeachcomma-operator

comma operator with c++11 for loop


I wanted at first to try if it was allowed to do something like :

vector<int> a{1, 2};
vector<int> b{3, 4};

for(auto ai : a, auto bi : b)
{

}

This didn't work but I was expecting it because of the size constraint.

However, I was surprised that this didn't work either :

vector<int> b{3, 4};

for(int x = 1, auto bi : b)
{

}

Isn't the comma operator meant to resolve every side effect of its left-side before going on the right side ?


Solution

  • In the second case you have a declaration. Declarations can contain declarations of multiple variables, separated by a comma.

    What you're writing in the second case is equivalent to the following declaration

    int x = 1, auto bi;
    
    for (...) ...
    

    And the reason that the first didn't work is not because of any size constraint, but because of the syntax of a range for loop simply doesn't allow you to do something like that.