Reputation: 110380
Is it possible to do something like this in C?
for (int i=0, char c;;)
Or do the types need to match? What are the various possibilities for the assignment (first part) of the for
loop? For example:
for (int i,j,k=0;;)
for (int i=0, j, k=2;;)
for (int i=0, j=1, k;;)
for (int i, j=1, k;;)
...etc...
Upvotes: 1
Views: 255
Reputation: 23
The reason why you can't have
for (int i, char c;;)
is the same reason why you can't have
int i, char c;
In C, semicolons delimit each statement from the other, whereas commas divide a single statement into multiple parts. For example, in
int i, n;
there is a single initialization statement: int <vars>
. If you were to write int <vars> char <vars>
, that would be incorrect. This is because you have two initialization statements not divided by a semicolon. A comma cannot be used to turn the two statements into one, either. While a comma can divide a statement into smaller parts, it cannot merge two statements into one.
The for
loop may contain only three statements--one initial, one conditional, and one increment.
Because the initialization of a variable of another type would require an extra statement, it is impossible to do so.
PS: The reason why the final statement doesn't require a semicolon is because it is encapsulated within parentheses as an iteration statement from which the for
loop is dependent on.
Upvotes: 2
Reputation: 17454
The rules are the same as in any other declaration: you can declare multiple variables in the one declaration, as long as they are of the same type.
If you want to declare variables of different type, you will need multiple declarations, and therefore you will need to hoist at least some of them out of the loop preamble.
Each name introduced in a declaration may or may not be accompanied by an initialiser, so all four of your latter examples are valid.
On a subjective note, cramming three or more names into the declaration part of the loop preamble makes your code hard to read and to understand anyway, and is crying out for refactoring with the declarations listed more cleanly outside of the loop, using descriptive variable names. Two declared names is already pushing it (but has valid, accepted uses for more complex iterations).
Upvotes: 3