C语言 ISO C90 禁止在 C 中混合声明和代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13291353/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ISO C90 forbids mixed declarations and code in C
提问by Johan Kotlinski
I declared a variable in this way:
我以这种方式声明了一个变量:
int i = 0;
I get the warning:
我收到警告:
ISO C90 forbids mixed declarations and code
ISO C90 禁止混合声明和代码
How can I fix it?
我该如何解决?
回答by Johan Kotlinski
I think you should move the variable declaration to top of block. I.e.
我认为您应该将变量声明移动到块的顶部。IE
{
foo();
int i = 0;
bar();
}
to
到
{
int i = 0;
foo();
bar();
}
回答by John Bode
Up until the C99 standard, all declarations had to come before any statements in a block:
在 C99 标准之前,所有声明都必须出现在块中的任何语句之前:
void foo()
{
int i, j;
double k;
char *c;
// code
if (c)
{
int m, n;
// more code
}
// etc.
}
C99 allowed for mixing declarations and statements (like C++). Many compilers still default to C89, and some compilers (such as Microsoft's) don't support C99 at all.
C99 允许混合声明和语句(如 C++)。许多编译仍然默认为C89,和一些编译器(如微软)不支持C99可言。
So, you will need to do the following:
因此,您需要执行以下操作:
Determine if your compiler supports C99 or later; if it does, configure it so that it's compiling C99 instead of C89;
If your compiler doesn't support C99 or later, you will either need to find a different compiler that doessupport it, or rewrite your code so that all declarations come before any statements within the block.
确定您的编译器是否支持 C99 或更高版本;如果是,请对其进行配置,使其编译 C99 而不是 C89;
如果你的编译器不支持C99或更高版本,你要么需要找到一个不同的编译器不支持它,或者重写代码,使所有声明的块内的所有语句之前。
回答by Jens Gustedt
Just use a compiler (or provide it with the arguments it needs) such that it compiles for a more recent version of the C standard, C99 or C11. E.g for the GCC family of compilers that would be -std=c99.
只需使用编译器(或为其提供所需的参数),以便为更新版本的 C 标准、C99 或 C11 进行编译。例如,对于 GCC 系列的编译器,将是-std=c99.
回答by Ron Nuni
Make sure the variable is on the top part of the block, and in case you compile it with -ansi-pedantic, make sure it looks like this:
确保变量在块的顶部,如果你用 编译它-ansi-pedantic,确保它看起来像这样:
function() {
int i;
i = 0;
someCode();
}
回答by vmsnomad
To diagnose what really triggers the error, I would first try to remove = 0
为了诊断真正触发错误的原因,我会首先尝试删除 = 0
If the error is tripped, then most likely the declaration goes after the code.
If no error, then it may be related to a C-standard enforcement/compile flags OR ...something else.
如果错误被触发,那么声明很可能在代码之后。
如果没有错误,那么它可能与 C 标准强制/编译标志或...其他东西有关。
In any case, declare the variable in the beginning of the current scope. You may then initialize it separately. Indeed, if this variable deserves its own scope - delimit its definition in {}.
无论如何,在当前作用域的开头声明变量。然后您可以单独初始化它。事实上,如果这个变量值得拥有自己的范围 - 在 {} 中界定它的定义。
If the OP could clarify the context, then a more directed response would follow.
如果 OP 可以澄清上下文,那么将会有更直接的回应。

