简体   繁体   English

C ++:数组元素设置为0

[英]C++: Array Elements are set to 0

I have been using arrays for a while now. 我已经使用数组一段时间了。

I have a few questions that i need to ask. 我有几个问题要问。

Now I know i cant use an array without giving a value its element(s). 现在我知道我不能在不给其元素值的情况下使用数组。

For example this would give me an error 例如,这会给我一个错误

int fly[5];
cout << fly[4] << endl;

And if i print an element that doesn't have a set value it would give an error: 如果我打印没有设置值的元素,则会出现错误:

int fly[5];
fly[2] = 1;
cout << fly[4] << endl;

Now I found if I give 1 element of the array any number in the array intialization. 现在,我发现是否在数组初始化中给数组的1个元素赋予任何数字。 Then the rest of the elements are set to 0. 然后将其余元素设置为0。

So this code prints 0 所以这段代码打印0

int fly[5] = {15};
cout << fly[4] << endl;

Why does this happen. 为什么会这样。 Can anyone explain? 谁能解释?

It happens because the C++ language standard says it should happen. 发生这种情况是因为C ++语言标准说应该发生。 The standard says it should happen because it's sensible behaviour and saves a lot of typing in cases where you want a large array initialized. 该标准说,这应该发生是因为这是明智的行为,并且在您要初始化大型数组的情况下可以节省很多键入操作。

Your first couple of examples produce undefined behaviour, in that the value of those array elements can be anything, but they shouldn't "give an error". 您的前两个示例会产生不确定的行为,因为这些数组元素的值可以是任何值,但它们不应“给出错误”。 (A sufficiently clever compiler might issue a warning.) (一个足够聪明的编译器可能会发出警告。)

First of all, your first two examples are not guaranteed to give an error. 首先,不能保证您的前两个示例都会出错。 If they do not, they will compile and run with undefined behavior. 如果不这样做,它们将以未定义的行为进行编译和运行。 The last one has well-defined behavior. 最后一个具有明确定义的行为。 If you do not specify values for every element of an array, the remainder are initialized with the default value, in this case 0. 如果未为数组的每个元素指定值,则其余部分将使用默认值初始化,在这种情况下为0。

When you brace-initialize an array and the initializer is too short, the missing elements are value-initialized. 当您对数组进行花括号初始化并且初始化器太短时,缺少的元素将被值初始化。 For primitive types such as int , this means zero-initialization (ie the initial value is zero). 对于基本类型(例如int ,这意味着初始化为零(即初始值为零)。 For example, you can say int a[100] = {}; 例如,您可以说int a[100] = {}; to get an all-zero array. 获得全零数组。 Integers aren't special, though, and this works for default-constructible class types just as well. 但是,整数并不特殊,它也适用于默认可构造的类类型。

Your first two examples constitute undefined behaviour, since you are reading an uninitialized variable. 您的前两个示例构成了未定义的行为,因为您正在读取一个未初始化的变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM