Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Microsoft's C compiler want the variables at the beginning of the function?

Tags:

c++

c

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.

like image 874
yinyueyouge Avatar asked Apr 01 '09 13:04

yinyueyouge


People also ask

How does the C/C++ compiler work?

The C/C++ compiler compiles each source file separately and produces the corresponding object file. This means the compiler can only apply optimizations on a single source file rather than on the whole program. However, some important optimizations can be performed only by looking at the whole program.

Why do we need to define all variables before the function starts?

Show activity on this post. This is a tradition which comes from early C compilers, when compiler needs all local variable definitions before the actual code of function starts (to generate right stack pointer calculation).

What is the purpose of compiler optimization in C/C++?

The C/C++ compiler compiles each source file separately and produces the corresponding object file. This means the compiler can only apply optimizations on a single source file rather than on the whole program.

Why Visual C++ is better than other C++ compilers?

On the other hand, the Visual C++ compiler can spend a lot more time to spot other optimization oppor­tunities and take advantage of them. A great new technology from Microsoft, called .NET Native, enables you to compile managed code into self-contained executables optimized using the Visual C++ back end.


1 Answers

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).

like image 178
dwc Avatar answered Oct 20 '22 01:10

dwc