When programming in Visual Studio, if you happen to run across this error while trying to compile C code, one thing to check on is whether or not you're declaring your local variables inline. For whatever reason, Visual Studio hates this and issues a syntax error for the next line of code. One that's of no use whatsoever in helping to figure out what to do.
So, for example, if you have a function like:
int foo(int x)
{
assert(x != 0);
int y = 4/x;
return y;
}
You would need to rewrite your code like this:
int foo(int x)
{
int y;
assert(x != 0);
y = x/4;
return y;
}
Strange but true. I suspect there's an option somewhere to turn off the strictness of the compiler, but I haven't found it.
Hello,
I found an other cause on http://rt.cpan.org/Public/Bug/Display.html?id=12925
"microsoft C compiler wants all variables declared at top of function", which is what is being done in the second example.
That worked perfect for me.
Posted by: Johann | March 29, 2006 at 08:39 AM
It's no surprise that Microsoft's compiler wants the variables at the beginnig of the function: Standard C wants them there.
Atleast, this is what C89 defines. C99 allows variable declarations also in the middle of a function.
Posted by: Martin v. Löwis | April 08, 2006 at 01:25 PM
I don't think is necessarily at the beginning of the function, I think the variables have to be at the beginning of the scope you are in, like this
int function ( )
{
int x = 1;
int y = 0;
if( x )
{
int z = 0; //this is ok
}
}
Posted by: John | February 04, 2009 at 03:31 PM
The problem is you are using a C file. This means the compiler implements strict C rules. If you change your source file to a cpp type file, you will use the C++ compiler which is myuch more flexible
Posted by: Shane Tuohy | October 23, 2009 at 11:36 AM
I was compiling a simple C program and came across this post (when the above described error came up for me) and I agree with @Johann and @Shane Tuohy both are true; just tested them :)
Posted by: Stefan___ | April 12, 2012 at 03:24 PM