第2章 变量和基本类型
Exercise 2.9
Explain the following definitions. For those that are illegal, explain what’s wrong and how to correct it.
(a)
std::cin >> int input_value;
(b)
int i = { 3.14 };
(c)
double salary = wage = 9999.99;
(d)
int i = 3.14;
(a): error: expected '(' for function-style cast or type construction.(?)
int input_value = 0;
std::cin >> input_value;
(b):when you compile the code without the argument "-std=c++11
", you will get the warning below: warning: implicit conversion from 'double' to 'int' changes value from 3.14 to 3.
when you compile the code using "-std=c+11
", you will get a error below: error: type 'double' cannot be narrowed to 'int' in initializer list
conclusion: Obviously, list initialization becomes strict in c++11.
double i = { 3.14 };
(c): --if you declared 'wage' before, it's right. Otherwise, you'll get a error: error: use of undeclared identifier 'wage'
double wage;
double salary = wage = 9999.99;
(d): ok: but value will be truncated(截断).
double i = 3.14;
Exercise 2.10
What are the initial values, if any, of each of the following variables?
std::string global_str;
int global_int;
int main()
{
int local_int;
std::string local_str;
}
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 not uninitialized, so it has a undefined value.
local_str
is also a local variable which is not 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.
定义于函数内部体内的内置类型的对象如果没有初始化,则其值 未定义。
类的对象如果没有显式地初始化,则其值 由类决定。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。