Question

Possible Duplicate:
Is it possible to declare two variables of different types in a for loop?

Consider this code:

for( std::vector<std::string>::iterator it = myVec.begin(), int i = 3; it < myVec.end(); it++, i++ )
{
// some operations with the vector
}

I got very surprised that MSVC 2010 gave me errors compiling this for loop. Is using comma operator forbidden by MSVS?

Here is an error:

error C2062: type 'int' unexpected 
error C2143: syntax error: missing ';' before ')'

If I try to push the "int i" definition out of the loop, I get:

error C2440: 'initializing': cannot convert from 'int' to 'std::vector'
Was it helpful?

Solution

A comma operator should have two expressions as operands. On its right hand side, you have int i=0 which looks like a declaration, not an expression.

If you remove that int, you are declaring a std::vector<std::string>::iterator variable named i and assigning or constructing it with 3 which does not type-check.

In practice, move the int i=3; declaration before (and out of) your for loop.

OTHER TIPS

you cant have a declaration for two different data types in the for loop, so you need to push the vector or i inside the loop, but you could assign the values

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