c++ - C++ 标准规定的整数范围

标签 c++

这个问题是关于 C++ 标准对基本整数类型的范围施加了什么。在 C++17 标准中,点 6.9.1在基本类型上有一点 4它说:

Unsigned integers shall obey to the laws of arithmetic modulo 2^n where n is the number of bits in the value representation of that particular size of integer.

在C标准中,它只说如果[0, max]是可以用无符号整数表示的范围,所有超出此范围的操作都以模 range + 1 为模进行缩减.它从不说range + 1应该是 2 的幂。

引用 C++ 标准是否意味着所有无符号整数都具有 [0, 2^n - 1] 类型的范围? ?我们可以从这一点推断出所有有符号整数的范围都是 [-2^(n/2), 2^(n/2) - 1] 吗? ?

我在标准中看不到任何内容,但该标准的先前引用似乎暗示了这类事情。


PS:这个问题与此处重复给出的问题不同。链接的问题是关于为什么标准中不强制执行二进制补码。我的问题是关于实际标准中的内容。

最佳答案

我会在这里尝试一个答案,欢迎更正:

Unsigned integers shall obey the laws of arithmetic modulo 2n where n is the number of bits in the value representation of that particular size of integer.

这意味着无符号整数的范围是[0, 2^n - 1],否则我看不出如何强制执行此操作。

[basic.fundamental]#3 — 重点是我的

For each of the standard signed integer types, there exists a corresponding (but different) standard unsigned integer type: “unsigned char”, “unsigned short int”, “unsigned int”, “unsigned long int”, and “unsigned long long int”, each of which occupies the same amount of storage and has the same alignment requirements as the corresponding signed integer type; that is, each signed integer type has the same object representation as its corresponding unsigned integer type. [...] The range of non-negative values of a signed integer type is a subrange of the corresponding unsigned integer type, the representation of the same value in each of the two types is the same, and the value representation of each corresponding signed/unsigned type shall be the same. [...]

据我所知,这些是链接有符号和无符号整数的唯一约束:

  • 第一点是相关的无符号和有符号整数使用相同的位数n表示;
  • 第二点是有符号整数的任何正值在相关无符号类型中具有相同的表示。

以下三种表示有符号整数的方法满足这些约束:Sign & Amplitude , Ones' complement , Two's complement .

正如我所读,标准中没有足够的约束来强制对有符号整数执行二进制补码表示。

关于c++ - C++ 标准规定的整数范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48612401/

相关文章:

c++ - 如何在 C++ 的外部类构造函数中初始化嵌套类成员

c++ - 在不重新洗牌的情况下随机选择 std::vector 的所有元素一次的有效方法

c++ - 在多线程中初始化 vector

c++ - 使用 C++ 编写的 Qt 文本编辑器的 UTF-16LE 编码问题

c++ - 使用 getline 读取文件时将值迭代到 vector 中

c++ - sscanf : retrieving int from a pattern with unknown occurrence number

c++ - -bash ./foo : No such file or directory after compilation

c++ - 删除字符串中的空格

c++ - 替换循环缓冲区/fifo 队列数组元素中的 "FOR()"宏

java - make 和 ant 的真正用途是什么?