Search code examples
c++for-loopscopeinitializervariable-declaration

Can I declare variables of different types in the initialization of a for loop?


Why does this C++ code not compile under VS2010:

for ( int a = 0, short b = 0; a < 10; ++a, ++b ) {}

while this one does:

short b = 0;
for ( int a = 0; a < 10; ++a, ++b ) {}

Is the declaration of two variables of different types inside the for-loop initializer prohibited? If so, how can you work around it?


Solution

  • Yes, that is prohibited. Just as otherwise you cannot declare variables of differing types in one declaration statement (edit: modulo the declarator modifiers that @MrLister mentions). You can declare structs

    for (struct { int a = 0; short b = 0; } d; d.a < 10; ++d.a, ++d.b ) {}
    

    C++03 code:

    for (struct { int a; short b; } d = { 0, 0 }; d.a < 10; ++d.a, ++d.b ) {}
    

    Of course when all are 0, you can omit the initializers altogether and write = { }.