gpt4 book ai didi

c - gcc 提示 : variable-sized object may not be initialized

转载 作者:太空狗 更新时间:2023-10-29 17:08:58 25 4
gpt4 key购买 nike

我看过这些,但它们没有回答我的问题:

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?


我正在尝试编写一些相当可移植的 c 代码:

int main () 
{
const int foo=13;
int bar[foo]={0};
return 0;
}

当使用以下任一方法编译为“c”代码时,出现“可变大小对象可能未初始化”错误:
  • 海湾合作委员会 4.3.4
  • arm-linux-gnueabi-gcc 4.4.5

如果我在 VS2008 中将它编译为 c,我会得到一个稍微不同的 error C2057: expected constant expression


据我所知,c 代码编译器无法将 const int foo=13; 识别为真正的常量;例如我们可能有

void a(int fool) 
{
const int foo=fool;
int bar[foo]={0};
}


我也意识到unlike the gcc compilers , VS2008 编译器没有 C99 variable-length arrays 的概念.而且那个 MS 显然没有提到任何 future 的支持。


然而,使用 gccMS 编译器的 cpp 代码编译是完全不同/更聪明的?!


还有关于 **gcc** `c` 代码编译器*我不明白*的是:
  • 因为这段代码可以编译,
int main () 
{
int bar[13]={0};
return 0;
}
  • 为什么这段代码编译..
int main()
{
const int foo=13; //cpp compiler knows this really is const !
int bar[foo]={0};
return 0;
}
  • 但是这段代码可以编译吗?
int main()
{
const int foo=13;
int bar[foo+1]={0}; //wtF?
return 0;
}


(注意:在最后一种情况下,MS c 代码编译失败;与 int bar[foo]={0} 一致;)

最佳答案

C99 §6.7.8 初始化是这样说的:

The type of the entity to be initialized shall be an array of unknown size or an object type that is not a variable length array type.

所以你的初始化无效C.

type a[size] 不是 VLA 的唯一方法是 size 是一个整数常量表达式(§6.7.5.2)。你所拥有的不是整数常量表达式,所以你有一个 VLA:

If the size is not present, the array type is an incomplete type. If the size is * instead of being an expression, the array type is a variable length array type of unspecified size, which can only be used in declarations with function prototype scope such arrays are nonetheless complete types. If the size is an integer constant expression and the element type has a known constant size, the array type is not a variable length array type; otherwise, the array type is a variable length array type.

第 §6.6/6 部分 常量表达式 将它们定义为:

An integer constant expression shall have integer type and shall only have operands that are integer constants, enumeration constants, character constants, sizeof expressions whose results are integer constants, and floating constants that are the immediate operands of casts. Cast operators in an integer constant expression shall only convert arithmetic types to integer types, except as part of an operand to the sizeof operator.

关于c - gcc 提示 : variable-sized object may not be initialized,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10129410/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com