Exercise 2.1

Questions

  1. What are the differences between int, long, long long, and short?
  2. Between an unsigned and a signed type?
  3. Between a float and a double?

Solutions

  1. Those types have different minimum sizes as listed in Table 2.1.



    And additional rules are included in the language to impose some restraints on those types. Here are some rules:

    • int will be not less than short
    • long will be not less than int
    • long long(C++11) will be not less than long
  2. A signed type can store positive or negative numbers (including zero).

    A unsigned type can only store non-negative numbers (i.e. numbers greater than or equal to zero).

  3. The specified minimum precision of double is greater than that of float. Typically, floats are represented in 32 bits, doubles in 64 bits.

Exercise 2.2

Question

To calculate a mortgage payment, what types would you use for the rate,

principal, and payment? Explain why you selected each type.

Solution

double.

https://www.investopedia.com/mortgage/mortgage-rates/payment-structure/

Exercise 2.3

Question

What output will the following code produce?

  1. unsigned u = 10, u2 = 42;
  2. std::cout << u2 - u << std::endl;
  3. std::cout << u - u2 << std::endl;
  4. int i = 10, i2 = 42;
  5. std::cout << i2 - i << std::endl;
  6. std::cout << i - i2 << std::endl;
  7. std::cout << i - u << std::endl;
  8. std::cout << u - i << std::endl;

Solution

  1. unsigned u = 10, u2 = 42;
  2. std::cout << u2 - u << std::endl; // 32
  3. std::cout << u - u2 << std::endl; // -32 + 2^32
  4. int i = 10, i2 = 42;
  5. std::cout << i2 - i << std::endl; // 32
  6. std::cout << i - i2 << std::endl; // -32
  7. std::cout << i - u << std::endl; // 0
  8. std::cout << u - i << std::endl; // 0

Exercise 2.4

Question

Write a program to check whether your predictions were correct. If not, study this section until you understand what the problem is.

Solution

  1. #include <iostream>
  2. int main()
  3. {
  4. unsigned u = 10, u2 = 42;
  5. std::cout << u2 - u << std::endl;
  6. std::cout << u - u2 << std::endl;
  7. int i = 10, i2 = 42;
  8. std::cout << i2 - i << std::endl;
  9. std::cout << i - i2 << std::endl;
  10. std::cout << i - u << std::endl;
  11. std::cout << u - i << std::endl;
  12. }

Exercise 2.5

Question

Determine the type of each of the following literals. Explain the differences among the literals in each of the four examples:

  1. (a) 'a', L'a', "a", L"a"
  2. (b) 10, 10u, 10L, 10uL, 012, 0xC
  3. (c) 3.14, 3.14f, 3.14L
  4. (d) 10, 10u, 10., 10e-2

Solution

  1. (a) 'a' (char), L'a' (wchar_t), "a" (char[]), L"a" (wchart_t [])
  2. (b) 10 (int), 10u (unsigned), 10L (long), 10uL (unsigned long), 012 (int), 0xC (int)
  3. (c) 3.14 (double), 3.14f (float), 3.14L (long double)
  4. (d) 10 (int), 10u (unsigned), 10.(double), 10e-2(double)

a.1:'a' is a character enclosed within single quotes that is a literal of type char.

a.2: L'a' is a character enclosed within single quotes and prefixed with a letter L that is a literal of type wchar_t.

a.3: "a" is a character enclosed within double quotes that is a literal of type string -- an array of constant chars.

a.4 L"a" is a character enclosed within double quotes and prefixed with a letter L that is a literal of type wstring -- an array of constant wchar_ts.

b.1: By default, the decimal literals are signed and the smallest type in which the literal value 10 can fit is int.

b.2: We override the default type of decimal literals by suffixing a letter u to the undecorated literal 10. It changes the signedness, the literal 10u has an unsigned type. The smallest unsigned type in which the number 10 can fit is unsigned.

b.3: ibid.

b.4: ibid.

b.5: 012 is an integer literal with a leading zero, we interpret this literal as octal. 012 in octal notation has a value of 10(in decimal notation). The smallest unsigned type in which the number 10 can fit is int.

b.6: ibid.

c.1: 3.14 is a floating-point literal that includes a decimal point(.). The default type for floating-point literals is double.

c.2: We override the default type of floating-point literals to float by using the suffix f.

c.3: ibid.

d.1: ibid.

d.2: ibid.

d.3: ibid.

d.4: 10e-2 is a floating-point literal that includes an exponent. The default type for floating-point literals is double.

Exercise 2.6

Question

  1. int month = 9, day = 7; // LINE 1
  2. int month = 09, day = 07; // LINE 2

Solution

The variables day in line 1 and line 2 have the same value of 7 in decimal notation.

In line 2, 09 is an invalid octal integer literal, because octal notation can only hold digits from 0 to 7, and 9 is an invalid octal digit.

Exercise 2.7

Question

What values do these literals represent? What type does each have?

  1. (a) "Who goes with F\145rgus?\012"
  2. (b) 3.14e1L
  3. (c) 1024f
  4. (d) 3.14L

Solution

(a) \145 is a generalized escape sequence, which is a \ followed by three octal digits. The octal numeral 145 has the value of 101(\(1 \times 8^2 + 4 \times 8^1 + 5 \times 8^0 = 101\)). ASCII table maps the number 101 to a lowercase letter e.


The octal numeral 012 has the value of 10, which represents a control character Line Feed(LF).


VALUE:

"Who goes with F\145rgus?\012" is equivalent to "Who goes with Fergus?\n".

TYPE: array of constant char

(b)

VALUE: 31.4

TYPE: long double

(c)

1024f is an invalid literal.

(d)

VALUE: 3.14

TYPE: long double

Exercise 2.8

Question

Using escape sequences, write a program to print 2M followed by a newline. Modify the program to print 2, then a tab, then an M, followed by a newline.

Solution

  1. #include <iostream>
  2. // Using escape sequences, write a program to print `2M` followed by a newline.
  3. // Modify the program to print `2`, then a `tab`, then an `M`, followed by a newline.
  4. int main()
  5. {
  6. // HEX OCT CHR
  7. // 32 062 '2'
  8. // 4D 115 'M'
  9. // 0A 012 '\n'
  10. // 09 011 '\t'
  11. std::cout << "\062\115\012" << std::endl; // OCT
  12. std::cout << "\x32\x4D\x0A" << std::endl; // HEX
  13. std::cout << "\062\x09\115\x0A" << std::endl; // MIXED
  14. return 0;
  15. }

Exercise 2.9

Question

Explain the following definitions. For those that are illegal, explain what’s wrong and how to correct it.

  1. (a) std::cin >> int input_value;
  2. (b) int i = { 3.14 };
  3. (c) double salary = wage = 9999.99;
  4. (d) int i = 3.14;

Solution

(a) Illegal. The right operand of >> can't be a definition. Extract the definition into a single statement and put it before the statement in which >> is included.

  1. int input_value;
  2. std::cin >> input_value;

(b) Illegal. It requires a narrowing conversion, which may lose data. Strip the outer curly braces off.

  1. int i = 3.14;

(c) Illegal. Variable Names should be separated by commas. The rewritten statement is as follows:

  1. double salary = 9999.99, wage = 9999.99;

(d) legal. It's a narrowing conversion of 3.14 from double to int. The fractional part is discarded, and only the integral part is kept.

Exercise 2.10

Question

What are the initial values, if any, of each of the following variables?

  1. std::string global_str;
  2. int global_int;
  3. int main()
  4. {
  5. int local_int;
  6. std::string local_str;
  7. }

Solution

  1. std::string global_str; // "" an empty string
  2. int global_int; // 0
  3. int main()
  4. {
  5. int local_int; // uninitialized
  6. std::string local_str; // "" an empty string
  7. }

Exercise 2.11

Question

Explain whether each of the following is a declaration or a definition:

  1. (a) extern int ix = 1024;
  2. (b) int iy;
  3. (c) extern int iz;

Solution

  1. (a) extern int ix = 1024; // Definition
  2. (b) int iy; // Definition
  3. (c) extern int iz; // Declaration

(a). Any declaration that includes an explicit initializer is a definition.

Exercise 2.12

Question

Which, if any, of the following names are invalid?

  1. (a) int double = 3.14;
  2. (b) int _;
  3. (c) int catch-22;
  4. (d) int 1_or_2 = 1;
  5. (e) double Double = 3.14;

Solution

  1. (a) int double = 3.14; // N, double is the reserved keyword
  2. (b) int _; // Y
  3. (c) int catch-22; // N, an identifier can't contain -(dash)
  4. (d) int 1_or_2 = 1; // N, an identifier can't begin with a digit
  5. (e) double Double = 3.14; // Y, identifiers are case-sensitive, Double is not the reserved keyword

Exercise 2.13

Question

What is the value of j in the following program?

  1. int i = 42;
  2. int main()
  3. {
  4. int i = 100;
  5. int j = i;
  6. }

Solution

  1. j = 100;

The second assignment statement uses the local object named i(100) rather than the global one.

Exercise 2.14

Question

Is the following program legal? If so, what values are printed?

  1. int i = 100, sum = 0;
  2. for (int i = 0; i != 10; ++i)
  3. sum += i;
  4. std::cout << i << " " << sum << std::endl;

Solution

Legal.

OUTPUT

  1. 100 45

The name i defined in the scope of the for statement hides the one defined outside the for statement.

Exercise 2.15

Question

Which of the following definitions, if any, are invalid? Why?

  1. (a) int ival = 1.01;
  2. (c) int &rval2 = ival;
  3. (b) int &rval1 = 1.01;
  4. (d) int &rval3;

Solution

(a) Legal. We assign 1.01 to ival.

(b) Legal. We bind the reference rval2 to ival.

(c) Illegal. A reference may not be bound to a literal.

(d) Illegal. References must be initialized.

Exercise 2.16

Question

Which, if any, of the following assignments are invalid? If they are valid, explain what they do.

  1. int i = 0 , &r1 = i;
  2. double d = 0, &r2 = d;
  3. (a) r2 = 3.14159;
  4. (b) r2 = r1;
  5. (c) i = r2;
  6. (d) r1 = d;

Solution

(a) Valid. We assign 3.14159 to the object to which r2 refers, i.e., to d.

(b) Valid. We assign the value of the object to which r1 refers (i.e. i) to the object to which r2 refers (i.e. d). In other words, we assign 0 to d.

(c) Valid. We assign 3.14159 to i. The value is truncated. i has the value of 3.

(d) Valid. ibid.

Exercise 2.17

Question

What does the following code print?

  1. int i, &ri = i;
  2. i = 5; ri = 10;
  3. std::cout << i << " " << ri << std::endl;

Solution

  1. 10 10

ri is an alias of i.

We change the value of i if we change ri.

Exercise 2.18

Question

Write code to change the value of a pointer. Write code to change the value to which the pointer points.

Solution

  1. #include <iostream>
  2. // Write code to change the value of a pointer. Write code to change the value
  3. // to which the pointer points.
  4. int main()
  5. {
  6. int a = 100;
  7. int *p = nullptr;
  8. p = &a; // change the value of a pointer
  9. *p = 1000; // change the value to which the pointer points
  10. std::cout << *p << std::endl;
  11. return 0;
  12. }

Exercise 2.19

Question

Explain the key differences between pointers and references.

Solution

Similarities

  • Both are used for indirect access to other objects.

Differences

  • References must be initialized, while pointers need not be initialized.
  • References may not be rebound to different objects, while pointers can point to different objects.
  • References must refer to a object, while pointers can point to a null pointer.

Exercise 2.20

What does the following program do?

  1. int i = 42;
  2. int *p1 = &i;
  3. *p1 = *p1 * *p1;

Solution

  1. int i = 42; // assign 42 to `i'
  2. int *p1 = &i; // `p' holds the address of `i'; `p' is a pointer to `i'
  3. *p1 = *p1 * *p1; // square the value of the object to which `p' points, i.e. `i'

Exercise 2.21

Question

Explain each of the following definitions. Indicate whether any are illegal and, if so, why.

  1. int i = 0;
  2. (a) double* dp = &i;
  3. (b) int *ip = i;
  4. (c) int *p = &i;

Solution

(a) Illegal. There is a mismatch between the type of dp and the object to which dp points.

(b) Illegal. We cannot assign an int variable to a pointer.

(c) Legal.

Exercise 2.22

Question

Assuming p is a pointer to int, explain the following code:

  1. if (p) // ...
  2. if (*p) // ...

Solution

  1. if (p) // check the value of p; 0/NULL/nullptr -> false; otherwise -> true
  2. if (*p) // check the value of the object to which p points; 0 -> false; nonzero -> true

Exercise 2.23

Question

Given a pointer p, can you determine whether p points to a valid object? If so, how? If not, why not?

Solution

NO. There is no way to distinguish a valid address from an invalid one.

Exercise 2.24

Question

Why is the initialization of p legal but that of lp illegal?

  1. int i = 42; void *p = &i; long *lp = &i;

Solution

A void* pointer can hold the address of any type.

The type of lp doesn't match the type of i.

Exercise 2.25

Question

Determine the types and values of each of the following variables.

  1. (a) int* ip, i, &r = i; (b) int i, *ip = 0; (c) int* ip, ip2;

Solution

(a)

ip: a pointer to int, undefined

i: int, undefined

r: a reference to int i

(b)

i: int, undefined

ip: a pointer to int, NULL

(c)

ip: a pointer to int

ip2: int

Exercise 2.26

Question

Which of the following are legal? For those that are illegal, explain why.

  1. (a) const int buf; (b) int cnt = 0;
  2. (c) const int sz = cnt; (d) ++cnt; ++sz;

Solution

(a) Illegal. A const object must be initialized.

(b) Legal.

(c) Legal.

(d) ++cnt is legal. ++sz is illegal, because const objects cannot be changed.

Exercise 2.27

Question

Which of the following initializations are legal? Explain why.

  1. (a) int i = -1, &r = 0;
  2. (b) int * const p2 = &i2;
  3. (c) const int i = -1, &r = 0;
  4. (d) const int * const p3 = &i2;
  5. (e) const int * p1 = &i2;
  6. (f) const int &const r2;
  7. (g) const int i2 = i, &r = i;

Solution

(a) The first half is legal, but the second one is illegal.

(b) Legal. p2 is a const pointer.

(c) Legal. We can bind a reference to const to a literal.

(d) Legal. p3 is a const pointer to a const object

(e) Legal. p1 is a pointer to a const object.

(f) Illegal. We cannot define a const reference; references must be initialized.

(g) Legal.

Exercise 2.28

Question

Explain the following definitions. Identify any that are illegal.

  1. (a) int i, * const cp;
  2. (b) int * p1, * const p2;
  3. (c) const int ic, &r = ic;
  4. (d) const int * const p3;
  5. (e) const int * p;

Solution

(a) N, a const pointer must be initialized.

(b) N, ID.

(c) N, ic must be initialized. r is a reference to a const object.

(d) N, p3 is a const pointer to a const object. ID.

(e) Y, p is a pointer to a const object.

Exercise 2.29

Question

Using the variables in the previous exercise, which of the following assignments are legal? Explain why.

  1. (a) i = ic;
  2. (b) p1 = p3;
  3. (c) p1 = &ic;
  4. (d) p3 = &ic;
  5. (e) p2 = p1;
  6. (f) ic = * p3;

Solution

(a) Y.

(b) N. p3 is a pointer to a const object.

(c) N. ic is a const object.

(d) N. We cannot rebind a const pointer to a new object.

(e) N. ID.

(f) N. A const object's value can not be changed.

Exercise 2.30

Question

For each of the following declarations indicate whether the object being declared has top-level or low-level const.

  1. const int v2 = 0;
  2. int v1 = v2;
  3. int * p1 = &v1, &r1 = v1;
  4. const int * p2 = &v2, * const p3 = &i, &r2 = v2;

Solution

v2: TOP

v1: NONE

p1: NONE

r1: NONE

p2: LOW

p3: TOP, LOW

r2: LOW

Exercise 2.31

Question

Given the declarations in the previous exercise determine whether the following assignments are legal. Explain how the top-level or low-level const applies in each case.

  1. r1 = v2;
  2. p1 = p2; p2 = p1;
  3. p1 = p3; p2 = p3;

Solution

  1. r1 = v2; // ok: copying the value of v2, top-level const in v2 is ignored
  2. p1 = p2; // no: p2 has a low-level const but p1 doesn't
  3. p2 = p1; // ok: we can convert int* to const int*
  4. p1 = p3; // no: p3 has a low-level const but p1 doesn't
  5. p2 = p3; // ok: p2 has the same low-level const qualification as p3

Exercise 2.32

Is the following code legal or not? If not, how might you make it legal?

  1. int null = 0, *p = null;

Solution

It is illegal to assign an int variable to a pointer, even if the variable's value happens to be 0.

Assign nullptr to p.

Exercise 2.33

Using the variable definitions from this section, determine what happens in each of these assignments:

  1. a = 42;
  2. b = 42;
  3. c = 42;
  4. d = 42;
  5. e = 42;
  6. g = 42;

Solution

  1. a = 42; // OK
  2. b = 42; // OK
  3. c = 42; // OK
  4. d = 42; // NO, we cannot assign an int to a pointer
  5. e = 42; // NO, ID.
  6. g = 42; // NO, we cannot change the value of const reference.

Exercise 2.35

Determine the types deduced in each of the following definitions. Once you’ve figured out the types, write a program to see whether you were correct.

  1. const int i = 42;
  2. auto j = i;
  3. const auto &k = i;
  4. auto * p = &i;
  5. const auto j2 = i, &k2 = i;

Solution

  1. const int i = 42;
  2. auto j = i; // int
  3. const auto &k = i; // const int &
  4. auto * p = &i; // const int *
  5. const auto j2 = i, &k2 = i; // const int, const int &

Exercise 2.36

In the following code, determine the type of each variable and the value each variable has when the code finishes:

  1. int a = 3, b = 4;
  2. decltype(a) c = a;
  3. decltype((b)) d = a;
  4. ++c; ++d;

Solution

  1. a: int 4
  2. b: int 4
  3. c: int 4
  4. d: int & 4

Exercise 2.37

Assignment is an example of an expression that yields a reference type. The type is a reference to the type of the left-hand operand. That is, if i is an int, then the type of the expression i = x is int&. Using that knowledge, determine the type and value of each variable in this code:

  1. int a = 3, b = 4;
  2. decltype(a) c = a;
  3. decltype(a = b) d = a;

Solution

  1. a: int 3
  2. b: int 4
  3. c: int 3
  4. d: int & 3

Exercise 2.38

Describe the differences in type deduction between decltype and auto. Give an example of an expression where auto and decltype will deduce the same type and an example where they will deduce differing types.

Solution

Both auto and decltype can deduce the type from a expression.

auto evaluates the expression as an initializer and assigns the return value to the variable.

decltype allows us to not use the expression to initialize the variable and even not evaluate the expression.

decltype deduces a reference type if the expression returns a left value.

decltype deduces a reference type if the variables is a reference type.

For a reference type, auto deduces a type of the object that the reference refers to.

Types deduced by decltype keep top-level const.

Types deduced by auto doesn't keep top-level const.

C++ Primer 5th Edition, Chapter 2, Solutions的更多相关文章

  1. C++ Primer 5th Edition自学笔记(1)

    好吧,第一次写东西...如何下手呢...(请无视) -------------------------------------------------------------- Chapter 1. ...

  2. 【C++ Primer 5th】Chapter 1

    1. 每个C++都包含至少一个函数,其中一个必须为main函数,且 main 函数的返回类型必须为 int. 2. 函数定义包括:返回类型,函数名,形参列表,函数体 3. main 函数返回值用来指示 ...

  3. 【C++ Primer 5th】Chapter 15

    摘要: 1. 面向对象程序设计的核心思想是数据抽象.继承和动态绑定.数据抽象将类的接口和实现分离:继承定义相似的类型并对齐相似关系建模:动态绑定,在一定程度上忽略相似类型的区别,而以统一的方式使用它们 ...

  4. C++Primer 5th 练习 12.19

    这阵子真是太忙了, 连续做了四个课设. 当然这并不能作为好久没写博客的借口, 没写博客的主要原因只有一个: 懒. 最近又开始回顾C++的语法与特性(据说C++就是一门需要反复回顾的语言),以及学习C+ ...

  5. 【读书笔记】C++ primer 5th 从入门到自闭(一)

    这几天看了C++ primer 5th的一二章,有很多收获,但是有的地方因为翻译的问题也搞得理解起来颇为难受啊啊啊啊.尤其是const限定符,在C语言并没有这么多复杂的语法,在C++里面语法细节就多的 ...

  6. C++ Primer 中文版 5th Edition 练习15.8和练习15.9的解答

    练习15.8:给出静态类型和动态类型的定义. 答: 静态类型:是变量声明时的类型,或者是表达式生成的类型,这样的类型在编译时已知. 动态类型:是变量或者表达式表示的内存中的对象的类型,直到运行时才可知 ...

  7. C++ Primer 5th 第1章 开始

    *****代码在Ubuntu g++ 5.31 / clang++ 3.8(C++11)下编写调试***** 每个C++程序必须有一个main( )函数,main( )函数的返回值也必须是int类型, ...

  8. c++ primer 5th 练习3.43

    #include <iostream> using namespace std; int main() { ][]={,,,,,,,,,,,}; /* for(int (&i)[4 ...

  9. C++ Primer 5th 第16章 模板与泛型编程

    模板是C++中泛型编程的基础,一个模板就是创建一个类或者函数的蓝图或者说公式. C++模板分为函数模板和类模板. 类模板则可以是整个类是个模板,类的某个成员函数是个模板,以及类本身和成员函数分别是不同 ...

  10. C++ Primer 5th 第15章 面向对象程序设计

    面向对象程序设计的核心思想是:数据抽象.继承和动态绑定. 数据抽象:将类的接口与实现分离: 继承:定义相似类型并对相似关系建模: 动态绑定:一定程度上上忽略相似类型间的区别,用同一方式使用它们. 1. ...

随机推荐

  1. java 1.8 API帮助文档

    链接:https://pan.baidu.com/s/1MNZqIokMDWNZF-nXnoHzxA 提取码:zw13

  2. 功能测试--APP专项

    APP测试重点 APP测试与web测试的区别 APP测试常见问题 APP日志分析 APP压力稳定性测试

  3. for in循环的坑

    num本来数个数组,但是for in把数组原型上的也遍历(偶尔会)记录一下坑,数组还是for循环,for in还是用在对象上好

  4. 我在迁移我的IDEA的项目、模块等东西的过程中发生过的一部分问题的我的一部分的记录以及我的解决方案如下

    使用idea2019阶段报的一些错: 1.'xxxServlet' is not assignable to 'javax.servlet.Servlet' 解决方案:把tomcat加入classpt ...

  5. 关于JDBC的学习

    一.JDBC简介 JDBC是连接java应用程序和数据库之间的桥梁. 什么是JDBC? Java语言访问数据库的一种规范,是一套API. JDBC (Java Database Connectivit ...

  6. 手写 Java HashMap 核心源码

    手写 Java HashMap 核心源码 手写 Java HashMap 核心源码 上一章手写 LinkedList 核心源码,本章我们来手写 Java HashMap 的核心源码. 我们来先了解一下 ...

  7. 【Beat】Scrum Meeting 3

    时间:2021年6月28日 1.各个成员今日完成的任务以及贡献小时数 姓名 今日完成任务 贡献小时数 鑫 进行软件测试,修改bug 4 荣娟 进行软件测试,修改bug 4 亚楠 进行软件测试,修改bu ...

  8. Java学习小总结它又又又又来啦!

    又到了输出总结的时候啦,话不多说,直接开始输出! 一.final final修饰符的主要作用就是强调它所修饰的板块的"最后"性: 若是修饰成员方法:那么成员方法不可以再被重写: 若 ...

  9. 陈大好:持续创造小而美的产品丨独立开发者 x 开放麦

    本文内容来自RTE NG-Lab 计划中「独立开发者 x 开放麦」活动分享,分享嘉宾独立开发者 @陈大好. 本次活动中,来自 W2solo 独立开发者社区的管理员 @Eric Woo 也以<独立 ...

  10. 声网 X Yalla:面对面不如线上见,中东年轻人最偏爱的语聊房是怎样“炼”成的?

    "实时互动的本质是服务,而非功能."这是声网一直以来坚信的理念. 功能上线之后,服务才真正开始.实时互动的每一秒,甚至每一毫秒的体验都需要得到稳定.可靠的保证.而广大用户之所以能够 ...