天天看點

error C2143: syntax error : missing ';' before 'type' in Visual C++

今天偶然寫了下面的程式(原來我寫的程式不一樣,下面的隻是為了把問題簡化)

void foo()

{

int p = 0;

if ( p == 0 )

int i = 0;

int a;

}

int main()

{

foo();

}

不幸的是偶然将這個檔案儲存成了test.c,然後編譯的時候出現了

error, error C2143: syntax error : missing ';' before 'type'

感覺很奇怪,細細看來所有的文法都似乎都是對的,更奇怪的是把檔案改成cpp或者cc能正常編譯,把int a;和if調換下也能正常編譯。這樣的錯誤可能發生在當變量的聲明放在可執行代碼之後。而這個是在K&R C中規定的,但在ANSI C中廢除。

MSDN (http://support.microsoft.com/kb/58559)給出的解釋如下:

In Microsoft C, compiler errors C2143 and C2144 are defined as follows:

    C2143: syntax error : missing 'token1' before 'token2'

    C2144: syntax error : missing 'token' before type 'type'

You may receive this error message if your program places executable code before a data declaration, an acceptable practice in Kernighan-and-Ritchie C. This practice has been outlawed in later versions of the ANSI drafts.

This error message will normally occur if a required closing curly brace (}), right parenthesis [)], or semicolon (;) is missing.

注: The C Programming Language的作者簡稱K&R,也是C語言之父, 經常用K&R C來和ANSI C做對比。這本書的第二版已經用ANSI.

我用的編譯器是VS2008, 看來微軟向來無視标準。

總結:

在 ANSI C或者C++中,在可執行代碼中随時定義變量是允許的,但是在K&R C中是不允許的,VS2008實作的C竟然是K&R C。注意這樣的錯誤也展現在VS中要是用for (int i = 0; i++; i<10)同時你的檔案名是.c的也會出現這樣的錯誤。

Code complete中讨論過變量名的最遲綁定有利于增加代碼的可讀性等。是以在VS中寫c要注意了。

本文來自CSDN部落格,轉載請标明出處:http://blog.csdn.net/fancylea/archive/2009/06/10/4256793.aspx