在没有 "expected ';' before '}' token" 的情况下在 C 中使用匿名数组

Usage of anonymous arrays in C without "expected ';' before '}' token"

我尝试在条件块中使用一些 "anonymous arrays"(不确定名称)。我有以下代码

if (({10, 20, 30})[0] == 10) {

我在 Windows (MSys) 和编译选项 -Wall -I/usr/include -Wextra -std=c99 -pedantic -Wno-unused-parameter 中使用 GCC 4.6.1 进行编译。它引发了以下警告和错误

my_code.c:1:9: warning: left-hand operand of comma expression has no effect [-Wunused-value]
my_code.c:1:13: warning: left-hand operand of comma expression has no effect [-Wunused-value]
my_code.c:1:17: error: expected ';' before '}' token

如果我在外部定义数组,它就可以正常工作:

int anonymous_array_01[3] = {10, 20, 30};
if (anonymous_array_01[0] == 10) {

出了什么问题(可能是与 GCC 版本或编译选项有关的错误)?

谢谢

这个构造

{10, 20, 30}[0]

没有意义。

改为使用复合文字

if ( ( int [] ){10, 20, 30}[0] == 10) 

文字的类型是什么{ 10, 20, 30 }?它是 int[3]double[3]long[3]char[3] 类型的数组文字还是结构文字(如果是,是哪种结构类型?)编译器需要类型信息您没有提供,因此编译错误。

解决方法是包含类型信息,创建一个格式正确的复合文字,它是您拥有的一组值,加上一个强制转换表达式:

(int[]){10, 20, 30}

您可以对结构执行相同的操作:

(struct{int x,y,z;}){10, 20, 30}

这个

if (({10, 20, 30})[0] == 10) {

没有意义。

这只不过是声明数组的错误方式。

可能是因为

{10,20,30,}

不调用数组。如果要比较,必须使用传统数组。