I was trying to do this in ANSI C:
include <stdio.h>
int main()
{
printf("%d", 22);
int j = 0;
return 0;
}
This does not work in Microsoft Visual C++ 2010 (in an ANSI C project). You get an error:
error C2143: syntax error : missing ';' before 'type'
This does work:
include <stdio.h>
int main()
{
int j = 0;
printf("%d", 22);
return 0;
}
Now I read at many places that you have to declare variables in the beginning of the code block the variables exist in. Is this generally true for ANSI C89?
I found a lot of forums where people give this advice, but I did not see it written in any ‘official’ source like the GNU C manual.
ANSI C89 requires variables to be declared at the beginning of a scope. This gets relaxed in C99.
This is clear with
gccwhen you use the-pedanticflag, which enforces the standard rules more closely (since it defaults to C89 mode).Note though, that this is valid C89 code:
But use of braces to denote a scope (and thus the lifetime of the variables in that scope) doesn’t seem to be particularly popular, thus C99 … etc.