I thought one could declare several variables in a for
loop:
for (int i = 0, char* ptr = bam; i < 10; i++) { ... }
But I just found out that this is not possible. GCC gives the following error:
error: expected unqualified-id before 'char'
Is it really true that you can't declare variables of different types in 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.
If your variables are the same type, you can define multiple variables in one declaration statement. For example: int age, reach; In this example, two variables called age and reach would be defined as integers.
There is no such thing as "construction" in C, so the space for the variable will simply be allocated into the stack (without any initialization), when the function is called. That's why there is a "zero" cost when declaring the variable inside a loop.
You can (but generally shouldn't) use a local struct type.
for ( struct { int i; char* ptr; } loopy = { 0, bam }; loopy.i < 10 && * loopy.ptr != 0; ++ loopy.i, ++ loopy.ptr ) { ... }
Since C++11, you can initialize the individual parts more elegantly, as long as they don't depend on a local variable:
for ( struct { int i = 0; std::string status; } loop; loop.status != "done"; ++ loop.i ) { ... }
This is just almost readable enough to really use.
C++17 addresses the problem with structured bindings:
for ( auto [ i, status ] = std::tuple{ 0, ""s }; status != "done"; ++ i )
It's true that you can't simultaneously declare and initialize declarators of different types. But this isn't specific to for loops. You'll get an error if you do:
int i = 0, char *ptr = bam;
too. The first clause of a for loop can be (C99 §6.8.5.3) "a declaration" or a "void expression". Note that you can do:
int i = 0, *j = NULL; for(int i = 0, *j = NULL;;){}
because i
and *j
are both of type int
. The exact syntax for a declaration is given in §6.7
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