问题描述
我看过这些,他们不回答我的问题:
我在编写一些相当便携的 c 代码:
int main()
{
const int foo = 13;
int bar [foo] = {0};
返回0;
}
我得到一个使用以下任一方法编译为 c 代码时,可能未初始化变量大小的对象错误
- gcc 4.3.4
- arm-linux-gnueabi-gcc 4.4.5
如果我在 VS2008 >我得到一个稍微不同的错误C2057:预期的常量表达式
我明白在这里, c 代码编译器无法识别 const int foo = 13; 是真正的常量;例如我们可能有
void a(int fool)
{
const int foo = fool;
int bar [foo] = {0};
}
我也意识到, VS2008 编译器没有。而且这个MS显然还没有提到任何未来的支持。
然而, cpp 代码编译与 gcc 或 MS 编译器是完全不同的/更聪明的?!
关于 gcc c 代码编译器的 :
- 自 编译,
- 为什么 没有 em> compile ..
- 然而 确实编译?
(注意:在这最后一种情况下, MS c 代码编译失败;与 int bar [foo] = {0}; )
一致。 p> C99§6.7.8初始化表示:
初始化无效C。
的唯一方式是将[size] 改为 not 是一个VLA是 size 是一个整型常量表达式(第6.7.5.2节)。你有什么不是整数常量表达式,所以你有一个VLA:
部分§6.6/ 6 常量表达式将它们定义为:
I've looked at these and they do not answer my question:
variable-sized object may not be initialized
C compile error: "Variable-sized object may not be initialized"
Error: Variable-sized object may not be initialized. But why?
I am trying to write some fairly portable c code:
int main () { const int foo=13; int bar[foo]={0}; return 0; }
I get a variable-sized object may not be initialized error when compiling as c code using either:
- gcc 4.3.4
- arm-linux-gnueabi-gcc 4.4.5
And if i compile it as c in VS2008 i get a slightly different error C2057: expected constant expression
I understand that here, the c code compiler is not recognising const int foo=13; to be truely constant; for example we might have
void a(int fool) { const int foo=fool; int bar[foo]={0}; }
I also realise that unlike the gcc compilers, the VS2008 compiler has no concept of C99 variable-length arrays. And that MS apparently has not mentioned any future support.
And yet, cpp code compilation with either gcc or MS compilers is altogether different/cleverer ?!
And also what i do not understand regarding the gcc c code compiler is:
(NB: in this last case, MS c code compilation fails; consistently as with int bar[foo]={0};)
C99 §6.7.8 Initialization says this:
So your initialization is invalid C.
The only way for type a[size] to not be a VLA is for size to be an integer constant expression (§6.7.5.2). What you have there is not an integer constant expression, so you have a VLA:
Part §6.6/6 Constant expressions defines them as:
这篇关于gcc抱怨:可变大小的对象可能未被初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!