在数组初始化器中有多余的元素可以吗? [英] Is it ok to have excess elements in array initializer?

查看:124
本文介绍了在数组初始化器中有多余的元素可以吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,当我们初始化数组时,我们可能会这样做:

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.

推荐答案

否,这不行。从C99开始,为6.7.8.2:

No, it's not OK. From C99, 6.7.8.2:


约束

Constraints


  1. 初始化程序不得尝试为未包含在正在初始化的实体中的对象提供值。


在我看来,这意味着提供过多的初始化器元素是约束违反,因此它会调用未定义的行为。

In my read, this means that providing excess initializer elements is a constraint violation, so it invokes undefined behavior.

这篇关于在数组初始化器中有多余的元素可以吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆