Multiple indices in for loop

M

mt

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) {}

Thanks,
 
K

Keith Thompson

mt said:
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.
 
M

Martin Ambuhl

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) {}

What makes you think you cannot do this? In pre-C99 compilers you need
to declare i and j outside the loop of course, but any C99 compiler
should like it as it stands.
 
J

J. J. Farrell

mt said:
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) {}

Thanks,

Impossible to answer (unless it does something different in Java than in
C, in which case I don't know).

Is it coincidence that "mt" is next door to "mu"?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top