c++ primer练习2.10

博客给出一段C++代码,探讨global_str、global_int、local_str、local_int的初始值。指出global_str是全局变量,值为空字符串;global_int是全局变量,值为0;local_int是未初始化局部变量,值未定义;local_str虽未初始化,但类内有定义,值为空字符串。

#include <iostream>

using namespace std;
string global_str;
int global_int;
int main()
{
int local_int;
string local_str;
cout<<"global_str:"<<global_str<<endl;
cout<<"global_int:"<<global_int<<endl;
cout<<"local_str:"<<local_str<<endl;
cout<<"local_int:"<<local_int<<endl;
}
问 global_str,global_int,local_str,local_int的初始值是多少

以下是程序运行结果

global_str:
global_int:0
local_str:
local_int:2002807738

Process returned 0 (0x0)   execution time : 0.081 s
Press any key to continue.

解释说明:global_str is global variable, so the value is empty string. global_int is global variable, so the value is zero. local_int is a local variable which is uninitialized, so it has a undefined value. local_str is also a local variable which is uninitialized, but it has a value that is defined by the class. So it is empty string. PS: please read P44 in the English version, P40 in Chinese version to get more. The note: Uninitialized objects of built-in type defined inside a function body have a undefined value. Objects of class type that we do not explicitly inititalize have a value that is defined by class.

global_str是一个全局变量,所以它的值是一个空字符串。global_int是一个全局变量,所以它的值是0。local_int是一个没有被初始化的局部变量,所以它是未被初始化的(详情可见c++ primer 第五版p33)。local_str是一个未被初始化的局部变量,但是在类的内部有定义的值,所以它是空字符串。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值