2

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'
Community
  • 1
  • 1
Igor
  • 4,364
  • 8
  • 38
  • 80
  • 2
    You mistyped something in your attempt to push it out of the for. If you don't show that code, we can't help you fix it. – Mat Nov 10 '12 at 09:27
  • @Mat, no everything seems to be order. Just checked. Thank you. – Igor Nov 10 '12 at 09:29
  • "everything seems to be in order" - if it was, your compiler wouldn't be telling you it's not. – Mat Nov 10 '12 at 09:30
  • I have to agree with Mat. I coded something very similar to yours and it compiled with no errors or warnings. (in MSVC of course) – MasterMastic Nov 10 '12 at 09:31

2 Answers2

7

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.

Basile Starynkevitch
  • 1
  • 16
  • 251
  • 479
  • +1 no 'looks like' about it. it *is* a declaration (to the OP), and it cannot be there unless it is first and singular (only one qualified decl type is allowed at the initialization-expression of a for-loop, last I checked. – WhozCraig Nov 10 '12 at 09:30
  • I don't know if we can say that it *is* a declaration. The C++ compiler refuses (rightly) to parse it, so we cannot say that it *is* a declaration to the compiler, just that, in this context, it *looks like* a declaration to humans. – Basile Starynkevitch Nov 10 '12 at 09:32
  • Sry. For the OP, it *is* a decl, for the compiler, its an invalid initialization expression =P – WhozCraig Nov 10 '12 at 09:33
0

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

Saddam Abu Ghaida
  • 5,445
  • 2
  • 17
  • 28