Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 825
grzkv Avatar asked Dec 27 '11 12:12

grzkv


People also ask

Can you initialize multiple variables in the initialization part of a for loop?

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.

Can you initialize variables in a for loop?

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.

Can you declare more than one variable in a for loop?

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.

How many variables can be initialized in for loop?

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.


1 Answers

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 = { }.

like image 163
Johannes Schaub - litb Avatar answered Oct 24 '22 05:10

Johannes Schaub - litb