[英]Is it ok to have excess elements in array initializer?
Usually when we initialize an array, we would probably do: 通常在我们初始化数组时,我们可能会这样做:
int arr[] = {1, 2, 3, 4, 5};
But is it ok to explicitly limit the length of the array as below? 但是可以明确地限制数组的长度如下所示吗? :
:
int arr[3] = {1, 2, 3, 4, 5};
Despite some warnings from the compiler, the executable doesn't seem to have any problems. 尽管编译器发出了一些警告,但可执行文件似乎没有任何问题。
No, it's not OK. 不,不行。 From C99, 6.7.8.2:
从C99,6.7.8.2:
Constraints
约束
- No initializer shall attempt to provide a value for an object not contained within the entity being initialized.
初始化程序不应尝试为未初始化的实体中包含的对象提供值。
In my read, this means that providing excess initializer elements is a constraint violation, so it invokes undefined behavior. 在我的阅读中,这意味着提供多余的初始化元素是违反约束的,因此它会调用未定义的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.