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?

unsigned u = 10, u2 = 42;
std::cout << u2 - u << std::endl;
std::cout << u - u2 << std::endl;
int i = 10, i2 = 42;
std::cout << i2 - i << std::endl;
std::cout << i - i2 << std::endl;
std::cout << i - u << std::endl;
std::cout << u - i << std::endl;

Solution

unsigned u = 10, u2 = 42;
std::cout << u2 - u << std::endl; // 32
std::cout << u - u2 << std::endl; // -32 + 2^32
int i = 10, i2 = 42;
std::cout << i2 - i << std::endl; // 32
std::cout << i - i2 << std::endl; // -32
std::cout << i - u << std::endl; // 0
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

#include <iostream>
int main()
{
unsigned u = 10, u2 = 42;
std::cout << u2 - u << std::endl;
std::cout << u - u2 << std::endl; int i = 10, i2 = 42;
std::cout << i2 - i << std::endl;
std::cout << i - i2 << std::endl;
std::cout << i - u << std::endl;
std::cout << u - i << std::endl;
}

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:

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

Solution

(a) 'a' (char), L'a' (wchar_t), "a" (char[]), L"a" (wchart_t [])
(b) 10 (int), 10u (unsigned), 10L (long), 10uL (unsigned long), 012 (int), 0xC (int)
(c) 3.14 (double), 3.14f (float), 3.14L (long double)
(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

int month = 9, day = 7;   // LINE 1
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?

(a) "Who goes with F\145rgus?\012"
(b) 3.14e1L
(c) 1024f
(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

#include <iostream>

// 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. int main()
{
// HEX OCT CHR
// 32 062 '2'
// 4D 115 'M'
// 0A 012 '\n'
// 09 011 '\t' std::cout << "\062\115\012" << std::endl; // OCT
std::cout << "\x32\x4D\x0A" << std::endl; // HEX std::cout << "\062\x09\115\x0A" << std::endl; // MIXED return 0;
}

Exercise 2.9

Question

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;

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.

int input_value;
std::cin >> input_value;

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

int i = 3.14;

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

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?

std::string global_str;
int global_int;
int main()
{
int local_int;
std::string local_str;
}

Solution

std::string global_str; // "" an empty string
int global_int; // 0
int main()
{
int local_int; // uninitialized
std::string local_str; // "" an empty string
}

Exercise 2.11

Question

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

(a) extern int ix = 1024;
(b) int iy;
(c) extern int iz;

Solution

(a) extern int ix = 1024; // Definition
(b) int iy; // Definition
(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?

(a) int double = 3.14;
(b) int _;
(c) int catch-22;
(d) int 1_or_2 = 1;
(e) double Double = 3.14;

Solution

(a) int double = 3.14;    // N, double is the reserved keyword
(b) int _; // Y
(c) int catch-22; // N, an identifier can't contain -(dash)
(d) int 1_or_2 = 1; // N, an identifier can't begin with a digit
(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?

int i = 42;

int main()
{
int i = 100;
int j = i;
}

Solution

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?

int i = 100, sum = 0;

for (int i = 0; i != 10; ++i)
sum += i; std::cout << i << " " << sum << std::endl;

Solution

Legal.

OUTPUT

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?

(a) int ival   = 1.01;
(c) int &rval2 = ival;
(b) int &rval1 = 1.01;
(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.

int i = 0   , &r1 = i;
double d = 0, &r2 = d; (a) r2 = 3.14159;
(b) r2 = r1;
(c) i = r2;
(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?

int i, &ri = i;
i = 5; ri = 10;
std::cout << i << " " << ri << std::endl;

Solution

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

#include <iostream>

// Write code to change the value of a pointer. Write code to change the value
// to which the pointer points. int main()
{
int a = 100; int *p = nullptr; p = &a; // change the value of a pointer *p = 1000; // change the value to which the pointer points std::cout << *p << std::endl;
return 0;
}

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?

int i = 42;
int *p1 = &i;
*p1 = *p1 * *p1;

Solution

    int i = 42;      // assign 42 to `i'
int *p1 = &i; // `p' holds the address of `i'; `p' is a pointer to `i'
*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.

int i = 0;
(a) double* dp = &i;
(b) int *ip = i;
(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:

if (p) // ...
if (*p) // ...

Solution

if (p) // check the value of p; 0/NULL/nullptr -> false; otherwise -> true
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?

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.

(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.

(a) const int buf; (b) int cnt = 0;
(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.

(a) int i = -1, &r = 0;
(b) int * const p2 = &i2;
(c) const int i = -1, &r = 0;
(d) const int * const p3 = &i2;
(e) const int * p1 = &i2;
(f) const int &const r2;
(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.

(a) int i, * const cp;
(b) int * p1, * const p2;
(c) const int ic, &r = ic;
(d) const int * const p3;
(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.

(a) i = ic;
(b) p1 = p3;
(c) p1 = &ic;
(d) p3 = &ic;
(e) p2 = p1;
(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.

const int v2 = 0;
int v1 = v2;
int * p1 = &v1, &r1 = v1;
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.

r1 = v2;
p1 = p2; p2 = p1;
p1 = p3; p2 = p3;

Solution

r1 = v2;  // ok: copying the value of v2, top-level const in v2 is ignored
p1 = p2; // no: p2 has a low-level const but p1 doesn't
p2 = p1; // ok: we can convert int* to const int*
p1 = p3; // no: p3 has a low-level const but p1 doesn't
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?

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:

a = 42;
b = 42;
c = 42;
d = 42;
e = 42;
g = 42;

Solution

a = 42; // OK
b = 42; // OK
c = 42; // OK
d = 42; // NO, we cannot assign an int to a pointer
e = 42; // NO, ID.
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.

const int i = 42;
auto j = i;
const auto &k = i;
auto * p = &i;
const auto j2 = i, &k2 = i;

Solution

const int i = 42;
auto j = i; // int
const auto &k = i; // const int &
auto * p = &i; // const int *
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:

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

Solution

a: int 4
b: int 4
c: int 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:

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

Solution

a: int 3
b: int 4
c: int 3
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. kg record

    参考资料: https://www.kaggle.com/youngyang/a-different-eda-based-on-qlib-en

  2. Oracle表主键作为外键都用在哪些表查询

    Oracle中,如果设置了外键,删除数据时,必须将外键关联一并删除,但是如果对项目不是很熟悉时,我们无法判断到底都在哪些表中有外键关联,以下提供了一个查询的SQL,可以通过数据库查询,查找到所有的外键 ...

  3. oralce 11g 数据库及客户端client等的下载安装

    下载地址:https://www.oracle.com/cn/database/technologies/microsoft-windows.html

  4. python 调试 qml

    1.设置pycharm的parameters -qmljsdebugger=port:10002,block 2.python 启动调试: 点击debug按钮 3.设置qt creater qt cr ...

  5. 21206134-赵景涛-第三次blog总结

    一.前言: 本次Blog是对之前发布的PTA题目集的总结性Blog,这几次的作业题量,难度都不大,但都趋近于完成一整个系统,而非只实现部分的功能.题目集九.十也不在给出类图,而是要求自己设计.我认为这 ...

  6. c# 递归应用 完成js文件自动引用

    背景: 两张表,分别是 :sys_tbl,和 sys_field,其中:sys_tbl 是系统所有表的信息,包含两个字段 :code(表名),name(表描述信息):sys_fld 是记录第张表中的字 ...

  7. Spring--注解开发+依赖注入

    自动装配 数据层: 业务层: 自动装配: 结果: 若是将自动装配的注解放在set函数处: 结果: 结果相同,若是将set方法去掉的话: 结果: 这样的话,set方法也得到解放了耶! 以上都是按照类型装 ...

  8. 声网自研传输层协议 AUT 的落地实践丨Dev for Dev 专栏

    本文为「Dev for Dev 专栏」系列内容,作者为声网大后端传输协议负责人 夏天. 针对实时互动应用对网络传输带来的新需求和新挑战,声网通过将实时互动中的应用层业务需求与传输策略的分层和解耦,于 ...

  9. 【读书笔记】排列研究-置换角度(分解为Products Of Cycles) 含GroupExploer使用

    upd 2020-08-06 23:11完成了最初稿 目录 定义 开胃菜 entrée 群论角度 应用:几何变换 当然要从第一类斯特林数的角度来考虑一下 一个排列的type定义 排旗公式 应用-共轭排 ...

  10. 中高等DP总结(更新中

    1.CF613D Kingdom and its Cities 题意:给定一棵树,每个询问给出一些关键点,要求删掉最少的点使这些点两两不联通,无解输出-1. 思路:先判无解:只要有一个关键点的父亲也是 ...