帮同事 debug 时,看到如下的 C 代码:用中括号里的数值,指定元素在数组中的次序。第一次见这种用法,验证一下。
#include <stdio.h>
int main(int argc, char* argv[])
{
int arr[10] = {
[9] = 9,
[3] = 3,
[4] = 4,
[2] = 2,
};
for(int i = 0; i < 10; ++i)
printf("%d ", arr[i]);
}
执行 gcc main.cpp
编译,报错:sorry, unimplemented: non-trivial designated initializers not supported
改用 gcc main.c
成功编译,输出结果:
0 0 2 3 4 0 0 0 0 9
C 支持数组的乱序初始化,其语法是在数组声明时,用 [INDEX] = value,
指定数组某个元素的初始值
C++ 是不支持乱序初始化的,想要在声明的时候初始化就必须按结构体里的顺序依次初始化
gcc 处理 .cpp 文件时,默认采用 C++ 编译器,g++ 处理
编译命令 | 默认编译规则 | 结果 |
---|---|---|
g++ main.cpp | C++ | 编译报错 |
gcc main.cpp | C++ | 编译报错 |
g++ main.c | C++ | 编译报错 |
gcc main.c | C | OK |
数组乱序初始化:sorry, unimplemented: non-trivial designated initializers not supported
原文:https://www.cnblogs.com/tengzijian/p/14966759.html