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?
In Java, multiple variables can be initialized in the initialization block of for loop regardless of whether you use it in the loop or not.
Often the variable that controls a for loop is needed only for the purposes of the loop and is not used elsewhere. When this is the case, it is possible to declare the variable inside the initialization portion of the for.
Yes, I can declare multiple variables in a for-loop. And you, too, can now declare multiple variables, in a for-loop, as follows: Just separate the multiple variables in the initialization statement with commas.
You can initialize as many as you want of any type, but should you use an inline declaration, all declared variables must be of the same type, as pst sort of mentioned.
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 = { }
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With