关于整数文字的 C++ Primer 段落,需要有人澄清一些要点

标签 c++ types literals

我目前正在学习《C++ Primer》(第 5 版),并且正在努力弄清楚作者在这部分文字中的含义(第 2 章,第 2.1.3 节):

... By default, decimal literals are signed whereas octal and hexadecimal literals can be either signed or unsigned types. A decimal literal has the smallest type of int, long, or long long (i.e., the first type in this list) in which the literal’s value fits. Octal and hexadecimal literals have the smallest type of int, unsigned int, long, unsigned long, long long, or unsigned long long in which the literal’s value fits. It is an error to use a literal that is too large to fit in the largest related type...

在第一句中,作者的意思是否是十进制文字是根据 C++ 标准进行签名的,而对于八进制和十六进制文字则取决于编译器?

接下来的三句话确实让我感到困惑,所以如果有人可以提供替代解释,我将不胜感激。

最佳答案

如果您有一个整数文字(例如十进制整数文字),则编译器必须定义其类型。例如,十进制文字可以在表达式中使用,编译器需要根据其操作数的类型来确定表达式的类型。

因此,对于十进制整数文字,编译器会在以下类型之间进行选择

int
long int
long long int

并选择第一种可以容纳十进制文字的类型。

它不考虑无符号整数类型,例如 unsigned int 或 unsigned long int,尽管它们可以容纳给定的文字。

当编译器处理八进制或十六进制整数文字时,情况有所不同。在这种情况下,它按给定顺序考虑以下类型

int
unsigned int
long int
unsigned long int
long long int
unsigned long long int

考虑一个人为的例子来证明这个想法会更清楚。假设您的值等于 127。该值可以存储在signed char类型中。现在值 128 怎么样?它不能存储在 signed char 类型的对象中,因为可以存储在 signed char 类型的对象中的最大正值是 127。

该怎么办?我们可以将 128 存储在 unsigned char 类型的对象中,因为它的最大值为 255。然而,编译器更喜欢将其存储在signed Short类型的对象中。

但是如果这个值被指定为0x80,那么编译器将选择一个unsigned char类型的对象

这当然是一个想象的过程。

然而,实际上,类似的算法用于十进制文字,只是编译器考虑从 int 开始的整数类型来确定十进制文字的类型。

关于关于整数文字的 C++ Primer 段落,需要有人澄清一些要点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31059402/

相关文章:

使用 mujoco-py 包的 MuJoCo 物理库的 Python 绑定(bind)

c# - 更改数据表列的类型

javascript - 使用 Javascript 设置 ASP 文字文本

C++11 operator""with double parameter

JavaScript 语法空 {}

c++ - C/C++ __restrict 类型

c++ - 拷贝构造函数、析构函数和临时变量

c - 当我在 int main() 之前声明 Shortf 函数时收到 "return type defaults to ' int' 警告。为什么?

c - 取消引用指向不完整类型的指针 [处理结构]

c++ - 与部分阵列作斗争