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);
}
-std=c99flag to GCC.i?-pedanticflag it will warn you about mixed declarations and code (and the comments). And if you compile with-Wallit'll be angry with you for not explicitly returning a value.for (int j = 0; j < 10; j++) { int some_var = 5; use_some_var(some_var); }.