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

Nathan Osman picture Nathan Osman · Apr 22, 2010 · Viewed 194k times · Source

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?

Answer

Georg Fritzsche picture Georg Fritzsche · Apr 22, 2010

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;
}