C++ 标准是否要求 非负 标准有符号整数类型的范围至少与负范围一样大?
编辑:请注意,我指的是 非负 范围在这里,而不是 正范围显然比 小一非负 范围。
编辑:如果我们假设 C++11,答案是"is"。请参阅下面的说明。从 C++03 的角度来看,答案很可能是否定的。
同样的问题可以提出如下:标准是否保证a - b
的结果?可以用标准的有符号整数类型表示 T
假设两者 a
和 b
是 负 T
类型的值,还有 a ≥ b
?
我知道该标准允许负值的二进制补码、一个补码和符号幅度表示(参见 C++11 第 3.9.1 节 [basic.fundamental] 第 7 段),但我不确定它是否需要使用这三种表示之一。可能不是。
如果我们假设这三种表示中的一种,并且假设对两个范围(负和非负)中的任何一个都没有“虚假”限制,那么非负范围确实至少为大为负。事实上,对于二进制补码,两个范围的大小将相等,而对于其他两种表示,非负范围的大小将比负范围的大小大 1。
然而,即使我们假设上述表示之一,也确实不足以保证任何一个范围的大小。
我在这里寻求的是明确提供所需保证的一个部分(或一组部分)。
任何帮助将不胜感激。
请注意,类似以下内容就足够了:整数的“存储槽”中的每一位都有一个,并且只有以下功能之一:
我有一个模糊的内存,C99 说了一些类似的话。任何对此有所了解的人?
好的,C99(带有 TC3)确实在第 6.2.6.2 节“整数类型”第 2 段中提供了必要的保证:
For signed integer types, the bits of the object representation shall be divided into three groups: value bits, padding bits, and the sign bit. There need not be any padding bits; there shall be exactly one sign bit. Each bit that is a value bit shall have the same value as the same bit in the object representation of the corresponding unsigned type (if there are M value bits in the signed type and N in the unsigned type, then M ≤ N ). If the sign bit is zero, it shall not affect the resulting value. If the sign bit is one, the value shall be modified in one of the following ways:
- the corresponding value with sign bit 0 is negated (sign and magnitude);
- the sign bit has the value −(2N ) (two’s complement);
- the sign bit has the value −(2N − 1) (ones’ complement ).
Which of these applies is implementation-defined, as is whether the value with sign bit 1 and all value bits zero (for the first two), or with sign bit and all value bits 1 (for ones’ complement), is a trap representation or a normal value. In the case of sign and magnitude and ones’ complement, if this representation is a normal value it is called a negative zero.
有人可以确认C99的这部分也是C++ 11的绑定(bind)部分吗?
我再次仔细查看了 C99 和 C++11 标准,很明显,C99 第 6.2.6.2 节第 2 段中的保证在 C++11 中也具有约束力。
C89/C90 不提供相同的保证,因此我们确实需要 C99,这意味着我们确实需要 C++11。
总之,C++11(和C99)提供了以下保证:
第二个保证可以重述如下:
-1 ≤ min<T> + max<T> ≤ 0
对于任何基本的有符号整数类型
T
(标准 + 扩展)其中 min<T>
和 max<T>
是 std::numeric_limits<T>::min()
的简写和 std::numeric_limits<T>::max()
分别。另外,如果我们假设
a
和 b
是相同或不同的基本有符号整数类型(标准或扩展)的值,则 a - b
在 decltype(a - b)
中定义明确且可表示只要a
和 b
要么都是负的,要么都是非负的。
最佳答案
尽管我可能遗漏了关键段落,但该标准似乎并未强制要求这样做。我们所知道的基本有符号整数类型都在 3.9.1/2 中:
There are five standard signed integer types : “signed char”, “short int”, “int”, “long int”, and “long long int”. In this list, each type provides at least as much storage as those preceding it in the list.
在 3.9.1/7 中:
Types bool, char, char16_t, char32_t, wchar_t, and the signed and unsigned integer types are collectively called integral types.48 A synonym for integral type is integer type. The representations of integral types shall define values by use of a pure binary numeration system.
这些段落似乎都没有说明各自的正负范围。即使考虑到我无法想象无法满足您需求的二进制表示。
关于c++ - 有符号 C++ 整数的非负范围是否至少与负范围一样大?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22204257/