C89 (C90, ANSI-C) 不允许将变量声明与代码混合使用。我想知道变量初始化在多大程度上被认为是“代码”。
也许只用常量表达式初始化才有效?
具体来说,如果我正在编写 C 代码并且我想保持安全(最大化与 ANSI-C 编译器的兼容性),以下内容是否应该被认为是安全的?
void f1(void) {
int x = 30;
int y = 40;
int z;
/* ... */
}
void f2(void) {
int x = 30, y = 40;
int z;
/* ... */
}
#define MYCONST (90)
void f3(void) {
int x = 3;
int y = 4 + MYCONST;
int z;
/* ... */
}
void f4(void) {
int x = 3;
int y = time(NULL);
int z = 10 + x;
/* ... */
}
最佳答案
should the following be considered safe?
您发布的所有代码都是安全的。
但是,在不是变量声明的代码之后声明变量是不合法的。
void foo()
{
int i = 0;
i = 2; // Does not declare a variable.
int j = 10; // Not legal.
}
上面的代码适用于 gcc。但是,如果您使用 -pedantic
标志,您将看到一条警告消息,如下所示:soc.c:5:4: warning: ISO C90 forbids mixed declarations and code [-Wpedantic]
int j = 10;
关于C89 和变量初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32786702/