I am currently writing a C (not C++). It seems the Microsoft’s C compiler requires all variables to be declared on top of the function.
For example, the following code will not pass compilation:
int foo(int x) { assert(x != 0); int y = 2 * x; return y; }
The compiler reports an error at the third line, saying
error C2143: syntax error : missing ';' before 'type'
If the code is changed to be like below it will pass compilation:
int foo(int x) { int y; assert(x != 0); y = 2 * x; return y; }
If I change the source file name from .c to be .cpp, the compilation will also pass as well.
I suspect there’s an option somewhere to turn off the strictness of the compiler, but I haven’t found it. Can anyone help on this?
Thanks in advance.
I am using cl.exe that is shipped with Visual Studio 2008 SP1.
Added:
Thank you all for answering! It seems I have to live in C89 with Microsoft’s cl.exe.
It looks like it’s using C89 standard, which requires that all variables be declared before any code. You may initialize them with literals, etc., but not mix code and variables.
There should be a compiler flag to enable C99 somewhere, which will get you the behavior you’re used to.
EDIT: quick Googling does not look promising for enabling C99. You may have to live with C89 (which ain’t so bad) or find a better C compiler (which would be better).