I'm curious about the following expression:
我对以下表达式很好奇:
int ints[] = { 1, 2, 3 };
This seems to compile fine even in c89 land with clang. Is there documentation about this? I can't seem to figure out the correct terminology to use when searching for it (and I'd rather not go through and read the entire c89 spec again).
即使在c89的土地上,这似乎也很好。有关于此的文件吗?我似乎无法弄清楚在搜索时使用的正确术语(我宁愿不再阅读并再次阅读整个c89规范)。
Is this an extension? Is the compiler simply inferring the size of the array?
这是延期吗?编译器只是简单地推断出数组的大小吗?
EDIT: I just remembered you guys like chunks of code that actually compile so here it is:
编辑:我记得你们都喜欢实际编译的代码块,所以这里是:
/* clang tst.c -o tst -Wall -Wextra -Werror -std=c89 */
int main(int argc, const char *argv[]) {
int ints[] = { 1, 2, 3 };
(void)(ints); (void)(argc); (void)(argv);
return 0;
}
2 个解决方案
#1
It's part of standard C since C89:
它是C89以来标准C的一部分:
§3.5.7 Initialization
If an array of unknown size is initialized, its size is determined by the number of initializers provided for its members. At the end of its initializer list, the array no longer has incomplete type.
如果初始化未知大小的数组,则其大小由为其成员提供的初始化程序的数量确定。在其初始化列表的末尾,该数组不再具有不完整的类型。
In fact, there is an almost exact example:
事实上,有一个几乎确切的例子:
Example:
The declaration
int x[] = { 1, 3, 5 };
defines and initializes
x
as a one-dimensional array object that has three members, as no size was specified and there are three initializers.将x定义并初始化为具有三个成员的一维数组对象,因为没有指定大小并且有三个初始值设定项。
#2
Is this an extension?
这是延期吗?
no, this is standard, for all versions of the C standard
不,这是C标准的所有版本的标准
by the =
the array type is "incomplete" and then is completed by means of the initialization
通过=数组类型是“不完整”然后通过初始化完成
Is the compiler simply inferring the size of the array?
编译器只是简单地推断出数组的大小吗?
yes
#1
It's part of standard C since C89:
它是C89以来标准C的一部分:
§3.5.7 Initialization
If an array of unknown size is initialized, its size is determined by the number of initializers provided for its members. At the end of its initializer list, the array no longer has incomplete type.
如果初始化未知大小的数组,则其大小由为其成员提供的初始化程序的数量确定。在其初始化列表的末尾,该数组不再具有不完整的类型。
In fact, there is an almost exact example:
事实上,有一个几乎确切的例子:
Example:
The declaration
int x[] = { 1, 3, 5 };
defines and initializes
x
as a one-dimensional array object that has three members, as no size was specified and there are three initializers.将x定义并初始化为具有三个成员的一维数组对象,因为没有指定大小并且有三个初始值设定项。
#2
Is this an extension?
这是延期吗?
no, this is standard, for all versions of the C standard
不,这是C标准的所有版本的标准
by the =
the array type is "incomplete" and then is completed by means of the initialization
通过=数组类型是“不完整”然后通过初始化完成
Is the compiler simply inferring the size of the array?
编译器只是简单地推断出数组的大小吗?
yes