1. Excerise 2.15: wht, if any , are the differences between the following definitionis:
int month = 9, day = 7;
int month = 09, day = 07;
Ans:两行定义都是变量的直接定义, 但是, 第二个定义的数据采用八进制数来初始化。但是09明显已经超出八进制数了。011
2. Excerise 2.16: assuming calc is a function that returns a double, which, if any, of the following are illegal definitions? Correct any that are identified as illegal.
(a) int car = 1024, auto = 2048; ans: auto是c++的关键字,不能用作变量标识符
(b) int ival = ival; ans: 木有问题。ival会被初始化为0.
(c) std::cin >>int pinput_value; 有问题, 编译器会认为int是另外一个语句的开始。
(d) double salary = wage = 9999.99; 木有问题,编译器报错,wage没有定义
(e) double calc = calc(); 有问题,编译器报错,calc不能用作function名。
3. Excerise 2.17 what ar eteh initial values, if any, of each of the following variables?
std::string global_str; //ans: 空串
int global_int; // ans:// ans: 0
int main()
{
int local_int; // ans: 0
std::string local_str; //ans: 空串
//...
return 0;
}
4. Exercises 2.18 Explain the meaning of each of these instances of name:
exterm std::string name; //声明变量name,说明他已经在其他地方定义了
std::string name("exercise 3.5a"); // 定义并且初始化变量name
extern std::string name("exercise 3.5a");// 定义一个变量
5. Exercises 2.19: what is the value of j in the following program?
int i = 42;
int main()
{
int i = 100;
int j = i; // ans: j is 9
}
6. Exercise 2.20 Givn the following program fragment, wat values are printed?
int i = 100, sum = 0;
for(int i =0; i !=10; ++i)
sum += i;
std::cout<<i<<" "<<sum<<std::endl; // ans: 100 45
7. Exercise 2.21 is the following program legal?
int sum = 0;
for (int i =0; i != 10; ++i)
sum += i;
std::cout<<"Sum from 0 to "<<i<<"is"<<sum<<std::endl; //ans: 编译错误,i没有定义
参考:
C++ primer 第四版