今天偶然寫了下面的程序(原來我寫的程序不一樣,下面的只是為了把問題簡化)
- void foo()
- {
- int p = 0;
- if ( p == 0 )
- int i = 0;
- int a;
- }
-
- int main()
- {
- foo();
- }
本文來自CSDN博客,轉載請標明出處:http://blog.csdn.net/fancylea/archive/2009/06/10/4256793.aspx
不幸的是偶然將這個文件保存成了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要注意了。