If C99 lifted "variable declaration at top of block" constraint, why doing so in a "for loop" showing error?

StackOverflow https://stackoverflow.com/questions/16664303

Question

I read from a site that C99 lifted the restriction that variables in C must be declared at the top of a block. I tested in my program below and it is indeed true as I get no errors. But in th e same program if I declare a variable in the first statement of a for loop, I get the error:

'for' loop initial declarations are only allowed in C99 mode|

Two things here. Since it is indeed allowed to declare variables in the middle of the program,as I did for i, why then I am not allowed to do that in a for loop statement? And second, if my compiler (Codeblocks/gcc) is not in C99 mode already, why didn't I get an error when I declared variables in the middle instead of the top?

#include <stdio.h>

int main (void)
{
  //Proof that initialization in middle works (for i)
  printf("Enter\n");
  char string[20];
  scanf("%s", string);
  int i=20;
  printf("%s,%i", string, i);
  //Proved that it works

  for(int j=0; j<10; j++) //THIS IS NOT ALLOWED
    printf("%d\n", j);
}
Was it helpful?

Solution

By default gcc compiles code with its own "dialect" which is an extension of C89. It is probably a good idea for new code and especially anybody learning C nowadays to pass to more modern and standardized version of the language. Unfortunately their implementation of C11 isn't yet complete, so you'd have to stick with C99 for the moment using -std=c99.

The gcc online documentation has information on the different dialects of C they implement.

An alternative compiler could be clang which is C99 by default. To my experience it is often better suited for beginners because the diagnostics are a bit more user friendly than gcc's.

OTHER TIPS

You use gcc : That enable some gcc specific extensions by default. Try :

[igmar@devel ~]$ gcc -std=c89 -pedantic -o xxx xxx.c
xxx.c: In function 'main':
xxx.c:6: warning: ISO C90 forbids mixed declarations and code
xxx.c:8: warning: ISO C90 forbids mixed declarations and code

-pedantic disabled the non-standard gcc extensions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top