当我在C ++中打印未初始化的变量时会发生什么? [英] What happens when I print an uninitialized variable in C++?

查看:118
本文介绍了当我在C ++中打印未初始化的变量时会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么打印 32767 (或其他一些随机数)?什么是 std :: cout 打印?为什么不是 NULL (或 0 )?

Why does this print 32767 (or some other random number)? What is std::cout printing? Why is it not NULL (or 0)?

int main() 
{
    int a;
    std::cout << a;
}


推荐答案

这是因为具有自动变量在C ++中,存储持续时间不会自动初始化为零。在C ++中,您无需为不需要的东西付费,并且自动将变量初始化需要花费时间(将存储位置设置为零最终会减少机器指令,然后将机器指令转换为控制物理位的电信号) )。

That is because variables with automatic storage duration are not automatically initialized to zero in C++. In C++, you don't pay for what you don't need, and automatically initializing a variable takes time (setting to zero a memory location ultimately reduces to machine intruction(s) which are then translated to electrical signals that control the physical bits).

该变量被保留在一个内存位置,并且碰巧该内存位置存在一些垃圾。该垃圾由 cout 打印。

The variable is being reserved a memory location, and it happens that some junk is at that memory location. That junk is being printed out by cout.

如@dwcanillas所指出的那样,这是不确定的行为。相关:在C中声明的未初始化变量会怎样?

As pointed out by @dwcanillas, it is undefined behaviour. Related: What happens to a declared, uninitialized variable in C? Does it have a value?

根据C ++标准(强调我的意思):

From the C++ standard (emphasize mine):

8.5初始化程序[dcl.init]


7)要默认初始化类型T的对象意味着



  • 如果T是(可能是具有简历资格的)类类型(第9条) ,则应考虑构造函数
    。枚举适用的构造函数(13.3.1.3),并通过重载分辨率(13.3)选择最适合初始化器()的
    。如此选择的
    构造函数将被调用,并带有一个空的参数列表以初始化>>对象。

  • 如果T是数组类型,则每个元素都将被默认初始化。 / li>
  • 否则,不执行初始化。

12) 如果未为对象指定初始化程序,则该对象将被默认初始化。当获得具有自动或动态存储持续时间的对象的存储时,该对象具有不确定的值,并且如果未对该对象执行任何初始化,则该对象将保留不确定的值,直到替换该值为止(5.18)。 [注意:具有静态或线程存储持续时间的对象将初始化为零,请参见3.6.2。 —尾注] 如果评估产生不确定的值,则行为是不确定的,但以下情况除外:

12) If no initializer is specified for an object, the object is default-initialized. When storage for an object with automatic or dynamic storage duration is obtained, the object has an indeterminate value, and if no initialization is performed for the object, that object retains an indeterminate value until that value is replaced (5.18). [Note: Objects with static or thread storage duration are zero-initialized, see 3.6.2. — end note ] If an indeterminate value is produced by an evaluation, the behavior is undefined except in the following cases:


-如果通过以下运算产生了无符号的窄字符类型的不确定值(3.9.1):

— If an indeterminate value of unsigned narrow character type (3.9.1) is produced by the evaluation of:

-条件表达式的第二个或第三个操作数(5.16),

— the second or third operand of a conditional expression (5.16),

-逗号表达式的右操作数(5.19),

— the right operand of a comma expression (5.19),

-逗号表达式的右操作数强制转换或转换为无符号的窄字符类型(4.7、5.2.3、5.2.9、5.4),或

— the operand of a cast or conversion to an unsigned narrow character type (4.7, 5.2.3, 5.2.9, 5.4), or

-舍弃值表达式(第5条)

— a discarded-value expression (Clause 5)

...


这篇关于当我在C ++中打印未初始化的变量时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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