In C , the question arises whether it's possible to declare variables of different types in the initialization body of a for loop. Consider the following code:
for(int i=0, j=0 ...
This initializes two integer variables (i and j). Is it possible to define an int and a char in this initialization body instead?
Technically, there is a workaround, albeit unconventional:
for(struct { int a; char b; } s = { 0, 'a' } ; s.a < 5 ; ++s.a) { std::cout << s.a << " " << s.b << std::endl; }
Here, we define a struct containing both an int and a char. The for loop initializes an instance of this struct, and then increments the int member within the loop body.
While this workaround satisfies the technical requirements, it's worth noting that this pattern is generally discouraged due to its potential for confusion and lack of clarity compared to using separate variables.
The above is the detailed content of Can You Declare Variables of Different Types in a C For Loop's Initialization?. For more information, please follow other related articles on the PHP Chinese website!