Question

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 ?

Was it helpful?

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top