mt <> writes:
> Why is it not possible to use multiple indices in a for loop in C like
> in java,
>
> Example:
> for (int i = 0, j= 0; i <= 10; i++,j = 2 * i) {}
It is, at least in C99. (I pasted your line of code into a C source
file, and gcc compiled it without complaint.)
If you're compiling in C90 mode, or using a compiler that doesn't
support C99, declarations in for loops aren't permitted at all.
But you might want to consider whether this is a good idea. You have a
loop invariant that j == 2 * i, but it's enforced in two different
places: the initial value of j (0), and the third clause of the for loop
(j = 2 * i). If those get out of sync, you've got problems.
For this particular case, you might try:
for (int i = 0; i <= 10; i ++) {
int j = 2 * i;
/* ... */
}
If you're declaring more than one variable in a for loop header,
you're probably trying to be too clever. (Note that you can't
declare, for example, an int and a char* together, just because of
the limitations of the syntax of a declaration).
FYI, the syntax for a for loop (C99 6.8.5p1) is:
for ( expression(opt) ; expression(opt) ; expression(opt) ) statement
for ( declaration expression(opt) ; expression(opt) ) statement
The second form is new in C99; the "declaration" provides the first
semicolon.
--
Keith Thompson (The_Other_Keith)
kst- <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"