未分配的值在int [] [英] unassigned value in the int[ ]

查看:154
本文介绍了未分配的值在int []的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想知道在C ++中 int [] 中未赋值整数的值通常是多少。

Would like to know in C++ what the value of unassigned integer in an int[] usually is.

示例

int arr[5];
arr[1]=2;
arr[3]=4;
for(int i=0;i<5;i++)
{
  cout <<arr[i] <<endl;
}

it print

-858993460
2
-858993460
4
-858993460

我们知道数组 {?,2,?,4,?}

?通常?

当我测试时,我总是得到负值。
我可以假设在C ++中未分配的元素在整数数组中总是小于或等于零?

When I tested , I always got negative value. Can I assume in C++ unassigned element in the integer array is always less than or equal to zero?

如果我错了,请更正。当我在Java学习时,未分配的数组元素将产生null。

Correct me if I'm wrong. When I study in Java unassigned element in array will produce null.

推荐答案

正式地,在大多数情况下,尝试读取未初始化值导致未定义的行为。

Formally, in most cases the very attempt to read an uninitialized value results in undefined behavior. So, formally the question about the actual value is rather moot: you are not allowed to even look at that value directly.

实际上,C和C ++中未初始化的值是不可预知的。最重要的是,它们不应该是稳定的,这意味着多次读取相同的未初始化值不能保证读取相同的值。

Practically, uninitialized values in C and C++ are unpredictable. On top of that they are not supposed to be stable, meaning that reading the same uninitialized value several times is not guaranteed to read the same value.

如果你需要一个pre - 初始化的局部数组,使用显式初始化器声明它

If you need a pre-initialized local array, declare it with an explicit initializer

int arr[5] = {};

以上是保证用整数零填充数组。

The above is guaranteed to fill the array with integer zeros.

这篇关于未分配的值在int []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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