views:

222

answers:

4

Is it possible to declare two variables of different types in the initialization body of a for loop in C++?

For example:

for(int i=0,j=0 ...

defines two integers. Can I define an int and a char in the initialization body? How would this be done?

+1  A: 

No, it is not possible.

sean e
+5  A: 

Not possible, but you can do

float f;
int i;
for (i = 0,f = 0.0; i < 5; i++)
{
  //...
}

or as some whould put it

{float f; 
int i;
for (i = 0,f = 0.0; i < 5; i++)
{
   //...
}}
MK
Ah. This seems like a good solution. I will look into this.
George Edison
+2  A: 

You can't declare multiple types in the initialization, but you can assign to multiple types E.G.

{
   int i;
   char x;
   for(i = 0, x = 'p'; ...){
      ...
   }
}

Just declare them in their own scope.

zipcodeman
+11  A: 

No - but technically there is a work-around (not that i'd actually use it unless forced to):

for(struct { int a; char b; } s = { 0, 'a' } ; s.a < 5 ; ++s.a) 
{
    std::cout << s.a << " " << s.b << std::endl;
}
Georg Fritzsche
upvoting for the wow.
MK
This does not compile on VS 2008, but does on Comeau online ;-)
JRL
Ya, +1 for sheer obfuscation
George Edison
@JRL: Oh, neither does VS2005. Yet another non-compliance feature in VC++ i guess.
Georg Fritzsche