C: for loop int initial declaration

for (int i = 0; ...) 

is a syntax that was introduced in C99. In order to use it you must enable C99 mode by passing -std=c99 (or some later standard) to GCC. The C89 version is:

int i;
for (i = 0; ...)

EDIT

Historically, the C language always forced programmers to declare all the variables at the begin of a block. So something like:

{
   printf("%d", 42); 
   int c = 43;  /* <--- compile time error */

must be rewritten as:

{
   int c = 43;
   printf("%d", 42);

a block is defined as:

block := '{' declarations statements '}'

C99, C++, C#, and Java allow declaration of variables anywhere in a block.

The real reason (guessing) is about allocating internal structures (like calculating stack size) ASAP while parsing the C source, without go for another compiler pass.

Leave a Comment