C++Primer Section 2-1

ICanPay is a payment gatSoft-wa ICanPay is a payment gatSoft-ware I/O pull-high/pull-down or open-drain control ˙1 internal interrupt source; 2 external interrupt sourceeway processing tools. 立即下载

Section 2-1 Primitive Built-in Types

The set of primitive built-in types are arithmetic types and a special type void.

Section 2-1-1 Arithmetic Types

Arithmetic types include characters, integers, boolean values and floating-point numbers.

But it can be divided into two categories—integers types and floating-point types.

Size of different types depends on machines. But the table gives the minimum size of each type.

TypeMeaningMinimum Size
boolbooleanNA
charcharacter8 bits
wchar_twide character16 bits
char16_tUnicode character16 bits
char32_tUnicode character32 bits
shortshort integer16 bits
intinteger16 bits
longlong integer32 bits
long longlong integer64 bits
floatsingle-precision floating-point6 significant digits
doubledouble-precision floating-point10 significant digits
long doubleextended-precision floating-point10 significant digits
Differences in Integer Types

Integer types include bool,char,wchar_t,char16_t,char32_t,short,int,long,long long.

Differences between char, wchar_t, char16_t and char32_t

char is guaranteed to be big enough to hold the basic set of characters in a machine, while wchar_t is guaranteed to be big enough to hold any character in the machine’s largest extended character set.

char16_t and char32_t are intended for Unicode characters.

Note

Sometimes the compiler will replace char by wchar_t or char16_t, char32_t.

Differences between short, int, long and long long

These four types are all intended for integers. The only difference between them is the size of them and the range of the number that they can represent.

But in different machines, those sizes and ranges change. But basically, we have the following rule:

sizeof(short) ≤ `sizeof(int)` ≤ sizeof(long) ≤ sizeof(long long)

Differences between in Floating-point Types
Differences between float, double and long double

These three types are all intended for floating-point number.

They have different sizes, precisions and purposes. Usually, float are represented in 1 word(32 bits). double in two words(64 bits) and long double in 3 or 4 words(96 or 128 bits).

The float and double types typically yield about 7 and 16 significant digits, respectively.

The type long double is often used as a way to accommodate special-purpose floating-point hardware.

Signed and Unsigned Types

Except for bool and the extended character types,, the integral types may be signed or unsigned.

A signed value can represent both negative an positive numbers by using special method. But an unsigned value can represent only 0 and positive numbers. and all bits in it represent the value.

int,short,long, long long are all signed types. To get corresponding unsigned types, we add unsigned to the type like unsigned long long.

unsigned int can be abbreviated as unsigned.

For characters, it is a little tricky since there will be three types char, singed char and unsigned char. But there are only two ways of representation signed and unsigned. Which type of representation char will take depends on the compiler.

Some people say that unsigned types are used to precisely control the machine-level or circuit-level operations instead of to enlarge the range of numbers that can be represented.

Good Practices for Using Arithmetic Types
  • Use an unsigned type when you know that the values cannot be negative
  • Use int for integer arithmetic. short is usually too small and , in practice, long often has the same size as int. If your number is too large, use long long.
  • Do not use plain char or bool in arithmetic expressions. Use them only to hold characters or truth values. Computations using char are especially problematic because char is signed on some machines and unsigned on others.
  • Use double for floating-point computations; float usually does not have enough precision, and the cost of double-precision calculations versus single-precision is negligible. In fact, on some machines, double-precision operations are faster than single. The precision offered by long double is usually unnecessary and often entails considerable run-time cost.
Exercises
Exercise 2.1

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

Solution

In part Differences in Integer Types and Differences in Floating-point Types

Exercise 2.2

To calculate a mortgage payment, what types would you use for the rate, principle, and payment? Explain why you selected each type.

Solution

All shall be double. All of them may be floating-point number and for floating-point computations we use double.

Section 2-1-2 Type Conversions In Assignment Statements

Type conversions take place wherever we expected one type of value while given another related type of value.

Basic Rules for Type Conversions in Assignment Statements
  • Assigning a nonbool arithmetic type to a bool type:

    result is false if the value is 0 and true otherwise

  • Assigning a bool to another arithmetic type of value:

    the result is 0 if the bool is false and 1 if the bool is true

  • Assigning a floating-point value to an object of integral type:

    The value will be truncated.

  • Assigning an integral value to an object of floating-point type

    Fraction part is 0. Precision may be lost if the integer has more bits than floating-point object can accommodate.

  • Assigning an out-of-range value to an object of unsigned type

    The result is the remainder of the value modulo the number of values the target type can hold. For example -1 to unsigned char will be 255

  • Assigning an out-of-range value to an object of signed type, the result is undefined.

Advice on how to use Type Conversions: Avoid undefined and implementation-Defined Behavior

Undefined behavior results from errors that the compiler is not required or able to detect, like the overflow of signed type. But this depends on the compiler, input and so on. So sometimes the program may work under a particular circumstance but fails under another.

Implementation-defined Behavior is about the portability of the program, meaning that when a program is moved from one platform to another, whether it can work as well as before. It has something to do with the features that vary between different platforms like the size of int.

A Typical Use of Type Conversion—Integer in Condition
int i = 0;

do something;

if (i) {
    do something;
}

In the block of code above. we have that the condition will evaluate as true is i≠0 . And the condition will evaluate as false if i=0 .

But it is worth noting that using bool in an arithmetic expression is highly NOT recommended.

Expressions Involving Unsigned Types
Arithmetic Expressions

If we use both an int and unsigned value in an arithmetic expression, the int will be converted to unsigned even if it is negative.

unsigned u = 10;
int i = -42;
std::cout << i + i << std::endl; // prints -84
std::cout << i + u << std::endl; // if 32-bit ints, prints 4294967264

So it is also important not to make the result of subtraction of unsigned negative.

unsigned u1 = 42, u2 = 10;
std::cout << u1 - u2 << std::endl;  // result is 32
std::cout << u2 - u1 << std::endl;  // result is -32 % MAX
Unsigned Type in Loop Condition
for (unsigned i = 10; i >= 0; i--) {    // intended to execute for 11 times but fails
    do something;
}

This loop shall never terminate because i is unsigned and can never fail the condition i≥0. But we can still do the following to compensate for it.

for (unsigned i = 11; i > 0; i++) {     // intended to execute for 11 times and succeed
    do something;
}
Tips On Using unsigned and signed

Do NOT mixed signed and unsigned Types!

signed value will be automatically converted to unsigned value. So mixing signed and unsigned type will yield surprising and even unpredictable results, especially when signed value is negative.

Exercise 2.3

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

The output should be

32

-32 % MAX

32

-32

0

0

MAX stands for the max number of unsigned + 1.

Exercise 2.4

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

Solution

The solution to 2.3 is right. And 32 % MAX is 4294967264.

Section 2-1-3 Literals

A literal refers to a value like 42 whose value is self-evident. Every literal has a type. The form and value will determine its type.

And we have three tables for the form of literal and the type of literals.

Table 1: Character and Character String Literals
PrefixMeaningType
uUnicode 16 characterchar16_t
UUnicode 32 characterchar32_t
Lwide characterwchar_t
u8utf-8(string literals only)char
Table 2: Integer Literals
SuffixMinimum Type
u or Uunsigned
l or Llong
ll or LLlong long
Table 3: Floating-Point Literals
SuffixType
f or Ffloat
l or Llong double

Actually, there is no negative literals because although the literal -42 seems a negative literal, it is actually composed of an operator - and a positive literal 42.

Integer and Floating-Point Literals
Integer Literals

We can write integer literals using decimal, octal or hexadecimal notation.

  • Integer literals that begin with 0 are interpreted as octal
  • Those that begin with either 0x or 0X are interpreted as hexadecimal
  • Decimal is decimal

For example

12      // decimal
012     // octal
0x14    // hexadecimal
How to determine integer literals’ type
  • A decimal literal has the smallest type of int, long, long long in which the literal’s value fits.
  • A octal or hexadecimal literal has the smallest type of int, unsigned, long, unsigned long, long long, unsigned long long in which the literal’s values fits.
  • No integer type has the type short
  • Those with suffix u or U can only be unsigned type which starts from unsigned to unsigned long long.
  • Those with suffix l, L, ll or LL has a minimum type as in the Table 2.
Tips on using suffix of integer literals

Use L instead of l which can be easily mistaken for 1.

Floating-Point Literals

We can write floating-point literals in two forms—normal notation with a decimal point or scientific notation with an exponent indicated by e or E.

For example

3.1415926    0.0     0e0     3.1E-4     0.    .1
How to determine a floating-point literal’s type
  • By default, they have the type double.
  • Every floating-point literal with suffix have its type determined by suffix as in Table 3.
Character and Character String Literals
Character Literals

A character enclosed within single quotes is a character literal.

How to determine a character literal’s type
  • By default, it has the type char.
  • Every character literal with prefix have its type determined by prefix as in Table 1.
Character String Literals

Zero or more characters enclosed within double quotation marks is a string literal.

  • The size of a string literal is one more than its apparent size with additional invisible character '\0' at the end of the string literal.

  • 'A' is different from "A".

  • Two string literals that appear adjacent to one another and that are separated only by spaces, tabs, or newlines are concatenated into one literal.

    For example

    std::cout << "a really, really long string literal "
            "taht spans two lines" << std::endl;
Escape Sequence

Two kinds of characters are in need of escape sequence:

  1. nonprintable characters

  2. characters with special purpose in language.

    For example

    // nonprintable
    \n       // newline
    \t       // horizontal tab
    \a       // alert(bell)
    \b       // backspace     
    // special purpose in language
    \\       // backslash
    \"       // double quote
    \'       // single quote    

In code

std::cout << '\n';  // a newline
std::cout << "\tHi!\n";     // a tab followed by Hi! followed by a newline
Generalized Escape Sequence

We can use generalized escape sequence, which is \x followed by one or more hexadecimal digits or a \ followed by one, two or three octal digits. The value represents the numerical value(usually ASCLL) of the character.

For example

\7      // bell
\12     // newline
\40     // blank
\0      // null
\115    // 'M'
\x4d    // 'M'    

In code

std::cout << "Hi \x4dO\115!\n";     // prints    Hi MOM! followed by a newline
std::cout << '\115' << '\n';        // prints    M followed by a newline
Boolean and Pointer Literals
Boolean Literals

true and false

Pointer Literals

nullptr

Exercises
Exercise 2.5

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) The first two are character literals and the last two are character string literals with two characters.

'a'     // type char
L'a'    // type wchar_t
"a"     // type const char*
L"a"    // type const wchar_t *    

(b) The first four are decimal literals and 012 is octal literal and 0xC is hexadecimal literal.

10      // int
10u     // unsigned int
10L     // long
10uL    // unsigned long    
012     // int
0xC     // int    

(c) They are all floating-point literals

3.14    // double
3.14f   // float
3.14L   // long double   

(d) The first two are integer literals and the last two are floating-point literals

10      // int
10u     // unsigned
10.     // double
10e-2   // double    
***Exercise 2.6

What, if any, are the differences between the following definitions:

int month = 9, day = 7;
int month = 09, day = 07;
Solution

The 09 seems an octal literal but there ought to be no 9 in octal literal. And 07 , though it is an octal literal, it does not make any difference. I was a little confused so I wrote a program and executed it.

The result is

2-6.cpp:5:14: error: invalid digit “9” in octal constant
int month = 09;
^

So this kind of expression is actually illegal.

Exercise 2.7

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). Who goes with Fergus? followed by a newline. const char * type

(b). 3.14 long double type

(c). 1024 float type

(d). 3.14 long double type

Exercise 2.8

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>

int main()
{
    std::cout << "\62\115\12";
    std::cout << "\62\t\115\12";

    return 0;
}
C++ primer习题第二章 Exercise 2.1: What are the differences between int, long, long long, and short? Between an unsigned and a signed type? Between a float and a double? Exercise 2.2: To calculate a mortgage payment, what types would you use for the rate, principal, and payment? Explain why you selected each type. 立即下载

相关推荐

VSCode里玩转AvaloniaUI:手把手教你搭建跨平台桌面应用开发环境(附.NET 7配置避坑)

本文详细介绍了如何在VSCode中搭建AvaloniaUI跨平台桌面应用开发环境,包括.NET 7配置避坑指南。从环境准备、项目创建到调试优化,手把手教你利用VSCode和Avalonia实现高效开发,特别解决了.NET 7依赖等常见问题,助力开发者快速上手跨平台应用开发。

weixin_28826545的博客 576

今天在群里遇到的一道很基础但是困扰了很多人的问题

 涵 vb(761624919) 20:57:18好吧  这个是一道题目 题意就是:下面程序段的运行结果是?  涵 vb(761624919) 20:38:10#includemain(){ int i,a;  for(a=1,i=-1;-1  {a++;printf("%2d",a);}  printf("%2d",i);} 这个为什么结果是-1?

star`blog 1116

Git GUI学习教程

学习宗旨:快速应用,不易忘记 很遗憾,申请Git的专栏未审批,那我就不再写专栏了,把最近的学习心得写一下,我也是在学习中进行,有任何问题直接留言,回复交流,我还采用思路+实践模式快速过。 目录 1、Git是什么 2、远程仓库 1)GitHub: 2)Gitee(码云): 3、安装Git(Windows) 1)下载 ...

Alexantao 的专栏 7250

沈阳师范大学大一上册C语言PTA题目集以及答案(第三章 循环结构程序设计 选择题篇)

沈阳师范大学大一上册C语言PTA题目集以及答案(第三章 循环结构程序设计 选择题篇) 2-1 The following piece of code prints out__. for (a=1,i=-1; -1<=i<1; i++) { a++; printf("%2d", a); } printf("%2d", i); (1分) B. -1 作者 往年试卷 单位 浙江大学 2-1 2-2 The following code fragment outputs the string str.

aanzz的博客 1万+

SDM660电源部分配置:

SDM660电源部分配置: Panel power supplies 1、Reference power supplies Description Name Regulator Voltage (V) Panel power supply 0 vddio PMIC 660/L11 1.8 Panel power supply 1 Lab PMIC 660/lab 4.6 Panel power s...

weixin_41811215的博客 4728

Pyrosim进阶指南:从隧道火灾模拟到复杂通风策略分析

本文深入探讨Pyrosim在隧道火灾模拟与通风策略分析中的高级应用。从精确几何建模到火源参数设置,再到通风系统的量化分析,详细介绍了如何利用Pyrosim优化隧道安全设计。特别强调了临界风速验证、横向通风配置及结果可视化技巧,为工程师提供实用的进阶指南。

weixin_30644369的博客 137

PTA题选

判断题: 任何表达式语句都是表达式加分号组成的。True C语言语句都有结束符 指向结构体变量的指针可以作函数参数,实现传址调用。True 结构体成员的类型必须是基本数据类型。False if(a=5) 是允许的。True (a=5)永远为真 假设有变量定义语句float f = 1234567890123.123456;,打印语句printf("f = %f", f); 的输出是f = 1234567954432.000000 。那么可以这样解释这种想象:因为float类型的数据精度是十进制7~.

分享我的idea 7658

数字图像处理:直方图匹配或规定化Histogram Matching (Specification)原理及感悟

本文介绍了连续图像和数字图像直方图匹配(直方图规定化)的原理、处理过程,并提供了案例进行了讲解。可以看到,直方图均衡处理是直方图匹配的一个重要桥梁。 最后,对于直方图规定化这个翻译个人觉得很low,个人感觉叫指定直方图更好理解,但Histogram Specification怎么翻译确实不太好把握,因此还是叫Histogram Matching直方图匹配最好。

老猿Python 2879

部分公司PHP面试题(供参考)

腾讯:1. 请对POSIX风格和兼容Perl风格两种正则表达式的主要函数进行类比说明 ereg preg_match ereg_replace preg_replace 2. 请说明在php.ini中safe_mode开启之后对于PHP系统函数的影响 3. PHP5中魔术方法函数有哪几个,请举例说明各自的用法 __sleep __wakeup __toString __set_state __

Jamesz' Blog 2595

安装openclaw时出现npm error code ENOENT npm error syscall spawn git报错的解决方案

本文主要介绍了安装openclaw时出现npm error code ENOENT npm error syscall spawn git报错的解决方案,希望能对使用openclaw的同学们有所帮助。 文章目录 1. 问题描述 2. 解决方案

weixin_43178406的博客 12万+

Python爬虫实战:亚马逊中国模拟登录与二次验证全解析(2026最新版)

在数据驱动的商业时代,亚马逊作为全球最大的电商平台,其商品数据、价格波动、评论信息、库存状态等对市场分析、竞品研究、价格监控具有极高的价值。然而,亚马逊的反爬虫机制堪称行业标杆——从请求指纹校验、动态令牌、行为分析到二次验证(2FA),层层设防。本篇文章将带你从零开始,使用2026年最新的Python技术栈,完整实现亚马逊中国(z.cn)的模拟登录,并攻克二次验证难题。郑重声明:本文仅限技术研究与个人学习用途,严禁用于批量抓取、价格劫持、账户爆破等违法违规行为。

2201_76125261的博客 377

C++ Primer Section 1-2

Section 1-2 Contents and Thoughts Objects for I/O Stream In the header iostream , four objects for I/O stream are defined. cin — standard input cout—standard output cerr—standard error—warnin...

fitzleopard的博客 249

寻路最终版哦

相信大家用unity3d寻路的时候,一定会碰到多人

yxriyin的专栏 6953

C++ Primer:Exercises Section 1.2.2

Exercise 1.3:编一个程序,在标准输出上打印“Hello, World”。 #include int main() { std::cout<<"Hello,World"<<std::endl; return 0; } Exercise 1.4:我们的程序利用内置的加法操作符“+”来产生两个数的和。编写程序,使用乘法操作符“*”产生两个数的积。 #include int ma

卖包子的大夫 589

android 蓝牙通讯demo

android 下蓝牙通讯demo,实现了发现蓝牙,使能蓝牙,通过蓝牙发送消息。

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

C++ Primer Memo(1) - Section2上

接下来一段时间,会将之前写阅读C++ Primer时做的一些笔记更新上来。 知识比较散碎,也会有很多不严谨的部分。发上来时我会再阅读、检查一次,将发现的错误纠正,但难免仍有疏漏之处,还望指正。 书用的是C++ Primer第四版,中英文对照。 斜体字部分是原文摘录,前缀“//”的注释部分是自己的笔记。 今天先更新最初的Section2前半部分。 C++ Primer Memo...

weixin_30364325的博客 100

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

C++ Primer:Exercises Section 2.1.2

Exercise 2.1: int、long 和 short 类型之间有什么差别? int 16位,short 16位,long 32位 Exercise 2.2: unsigned 和 signed 类型有什么差别? unsigned无符号型(大于等于0),signed带符号(任意数值) Exercise 2.3: 如果在某机器上 short 类型占 16 位,那么可以赋给 sho

卖包子的大夫 618

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

C++ Primer:Exercises Section 1.5.2

Exercise 1.24: 编写程序,读入几笔不同的交易。对于每笔新读入的交易,要确定它的 ISBN 是否和以前的交易的 ISBN 一样,并且记下每一个 ISBN 的交易的总数。通过给定多笔不同的交易来测试程序。这些交易必须代表多个不同的 ISBN,但是每个 ISBN 的记录应分在同一组。 Sales_item book1,book2,book3; Sales_item bookType

卖包子的大夫 735

C++ Primer:Exercises Section 1.4.2

Exercise 1.9: 下列循环做什么?sum 的最终值是多少? int sum = 0; for (int i = -100; i <= 100; ++i) sum += i; i从-100到100之间整数求和,最终全部中和,结果 为0 Exercise 1.10:用 for 循环编程,求从 50 到 100 的所有自然数的和。然后用 while

卖包子的大夫 497

C++Primer(第5版) Exercises Section 2.2.1

Exercise 2.9: Explain the following definitions. For those that are illegal, explain what’s wrong and how to correct it. (a) std::cin &gt;&gt; int input_value; (b) int i = { 3.14 }; (c) doub...

bensoho的博客 406

C++Primer(5th) Exercises Section 2.1.3

Exercise 2.5: 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...

bensoho的博客 497

C++primer的学习|section1.2. 初窥输入/输出

1.2. 初窥输入/输出C++ 并没有直接定义进行输入或输出(IO)的任何语句,这种功能是由标准库提供的。IO 库提供了大量的设施。然而,对许多应用,包括本书的例子而言,编程者只需要了解一些基本概念和操作。本书的大多数例子都使用了处理格式化输入和输出的 iostream 库。iostream 库的基础是两种命名为 istream 和 ostream 的类型,分别表示输入流和输出流。流是指要从某种 ...

qq_41245033的博客 177

C++ Primer Section 1-5

Section 1-5 Introducing Class Sales_item Class A class in C++ is a data structure, a type. When we look at a class, we should focus on the legal operations of it and not bother to care about the ...

fitzleopard的博客 186

C++ Primer:Exercises Section 2.2

Exercise 2.7: 解释下列字面值常量的不同之处。 (a) 'a',L 'a',"a",L"a" (b) 10, 10u, 10L, 10uL, 012, 0xC (c) 3.14, 3.14f, 3.14L (a)‘a’:单个字符a,L'a':宽单个字符a,“a”字符a与空字符,L"a"宽字符a与空字符 (b)10:整数,10U:无符号整数,10L:长整数型,10uL:

卖包子的大夫 797

c++ primer exercises section 4.1

Exercise 4.1 Assuming get_size is a function that taks no arguments and returns an int value, whic o the following definitions are illegal? Explain why? unsigned buf_siz = 1024; (a) int ia[buf_size]

Rachel Wang的little tree 578

C++ Primer:Exercises Section 1.5.1

Sales_item.h #ifndef SALESITEM_H #define SALESITEM_H #include #include class Sales_item { public: Sales_item(const std::string &book):isbn(book),units_sold(0),revenue(0.0){} Sales_item(std::istr

卖包子的大夫 689
上一篇: 整数划分问题(放苹果问题)(递归)
下一篇: 听课笔记---程序设计与算法(三)C++面向对象程序设计(郭伟老师)---第三周
FitzLeopard
博客等级 码龄9年 6粉丝 44原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值