1

This code compiles fine without errors.

#include <stdio.h>
#define N 10000

int main(void){
    int t;
    for(int i = 0, t = 1; i < 100; ++i){
        printf("%i\n", i);
    }
}

However, if you reverse the order of i and t, it won't compile.

#include <stdio.h>
#define N 10000

int main(void){
    int t;
    for(t= 1, int i = 0; i < 100; ++i){
        printf("%i\n", i);
    }
}

error: expected expression before int

Is this intentional? Why would it act like this? I'm using GCC with C11.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
MichaelX
  • 202
  • 1
  • 9
  • 1
    This has got nothing to do with the order of `t` or `i`, but with the type declaration inside of your loop. You can’t declare a variable type after the comma in your loop. Use `for (int i=0, t=1; ...)`. – Jens Apr 28 '17 at 12:04
  • NIce question. I punted an answer but have realised it would take an afternoon to answer correctly. You can probably figure out why yourself if you study the C grammar. See http://stackoverflow.com/questions/81656/where-do-i-find-the-current-c-or-c-standard-documents for good links. – Bathsheba Apr 28 '17 at 12:21
  • It is quite simple actually. `for(t= 1, int i = 0;` won't compile for the same reason as `t= 1, int i = 0;` won't compile. – Lundin Apr 28 '17 at 13:24

2 Answers2

6

The first snippet declares two new variables, i and t, for use in the loop.

The second code snippet is incorrect, because it mixes up an assignment with a declaration. C syntax of the for loop allows either a declaration or an assignment, but not both.

Note that variable t declared before the loop in the first snippet is separate from variable t which is used inside the loop:

int t = 100;
for(int i = 0, t = 1; i < 10 ; ++i, ++t){
    printf("%i %d\n", i, t);
}
printf("%d\n", t);

The value of t printed at the end remains 100, even though t inside the loop ends with a final value of 11 (demo).

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

It's not the order of the variable, it's the place of your type specifier int.

If you specify a type and then use one or more comma's that type is used for every variable after the comma:

int i, k, j; // i and j and k are all int's

You can't specify other types after a comma, you have to seperate those statements with a semicolon if you want to, which you obviously can't do in a for loop expression because the meaning is different.

Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122