简体   繁体   English

在for语句中声明变量时出错

[英]Error on Declaring variable in for statement

Is declaring a variable within for not allowed in C? 是否在C中不允许在中声明变量for Here is the code, 这是代码,

for(int i = 1; i<max; i++)

And I get error messages as, 我收到错误消息,

error C2143: syntax error : missing ';' 错误C2143:语法错误:缺少';' before 'type' 在“类型”之前
error C2065: 'i' : undeclared identifier 错误C2065:“ i”:未声明的标识符

It works if I declare the variable i jut before the for loop, 如果我在for循环之前声明突出的变量,则该方法有效,

int i;
for(i = 1; i<max; i++)

I was never expecting an error message on such a simple line of code. 我从未期望过在如此简单的代码行上出现错误消息。 Can you please help me explain the reason behind this? 您能帮我解释一下这背后的原因吗?

Edit: 编辑:
I've Visual C++ 2010 Express. 我有Visual C ++ 2010 Express。 I'm using the command line compiler cl . 我正在使用命令行编译器cl

Update: 更新:
Based on replies, I've found Visual C++ 2010 doesn't support C98. 根据答复,我发现Visual C ++ 2010不支持C98。

I've finally installed Visual Studio 2013 Express for Desktop which supports C98 and is working as expected. 我终于安装了Visual Studio 2013 Express for Desktop,它支持C98,并且按预期工作。
Thanks to all of you for the valuable information. 感谢大家提供的宝贵信息。

You are probably using pre-C99 standard compiler. 您可能正在使用C99之前的标准编译器。 In C89/ANSI C you have to declare variables in the beginning of the scope block. 在C89 / ANSI C中,您必须在作用域块的开头声明变量。 Pay attention to that because you will most likely get similar errors from declaring variables after you have made some function calls etc. 请注意这一点,因为在进行某些函数调用等操作之后,声明变量很可能会出现类似的错误。

MSVC is c89. MSVC是c89。 c89 is not allow this. c89不允许这样做。 use /TP option. 使用/TP选项。 This option is compiled C++ mode. 此选项是编译的C ++模式。

It's only allowed in C99. 仅在C99中允许。 Not sure what compiler you're using, clang and gcc have std=c99. 不确定您使用的是什么编译器,clang和gcc的std = c99。

它是C99,您的编译器可能太旧或未正确设置以使用此“新”标准。

Visual Studio is very poor when it comes to C and only supports a 24 years old, obsolete version of C called C90. 当涉及到C时,Visual Studio非常差,并且仅支持24年陈旧的C版本,称为C90。 And it supports that version poorly. 而且它对该版本的支持很差。 Microsoft has no strictly conforming C compiler. Microsoft没有严格符合要求的C编译器。

If you use a real C compiler instead, the code will compile just fine. 如果您使用真正的C编译器,则代码可以正常编译。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM