2

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 ?

dyp
  • 38,334
  • 13
  • 112
  • 177
Jean-Michaël Celerier
  • 7,412
  • 3
  • 54
  • 75

2 Answers2

4

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
2

The comma operator is an operator. Which means it can only be used in expressions. int x = 1, auto bi : b is definitely not an expression. So you cannot really use it there.

It looks a bit like a malformed declaration. Malformed because you're trying to change the type being declared.

Note that the grammar of the language actually uses a special nonterminal for-range-declaration for the piece on the left-hand side of :. Which eventually resolves to a single declaration. So it's illegal to declare more than one variable in the range-based for loop.

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455