在哪种情况下,c ++会将变量初始化为零? [英] On which occasions will c++ initialize variables with zero?
本文介绍了在哪种情况下,c ++会将变量初始化为零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在使用每个变量之前,应正确定义和初始化每个变量(为其分配一个值).但是在某些情况下,c ++会将变量的默认值设置为零.像下面的情况一样.
Every variable should be properly defined and initialized(assign a value to it) before being used. However under some circumstances, c++ will set variables with a default value of zero. Like the case below.
class A{
...
static int val;
...};
//int val = 10; //This is the usual definition.
int val;//Definition without assigning a value.
...
A a; //a class A object
std::cout<<a.val;
结果将为零.显然,编译器做了一些操作将变量a.val初始化为零.我很好奇他们什么时候会一般这样做?
The result would be zero. Obviously, the compiler did something to initialize variable a.val to zero. I am curious about when will they do this generally?
推荐答案
http://en.cppreference.com/w/cpp/language/zero_initialization
在以下情况下执行零初始化:
Zero initialization is performed in the following situations:
- 对于每个具有静态或线程本地存储持续时间的命名变量,在进行任何其他初始化之前.
- 作为值初始化(即为空非类类型以及没有构造函数的值初始化类类型的成员的一对括号或大括号)序列.
- 如果使用太短的字符串文字初始化字符数组,则数组的其余部分将被零初始化.
这篇关于在哪种情况下,c ++会将变量初始化为零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文