This is not a matter of recommended practise (nor undefined behavior), but about what the c++-standard actually guarantees in the matter of turning all bytes of an integer type to the value of (unsigned char)0
.
问题
在下面的代码片段中,是使用的表达式if 语句保证被评估为true in c++11 /questions/tagged/c%2b%2b11?
std::memset (
reinterpret_cast<char*> (&a), // int a;
(unsigned char)0,
sizeof (int)
);
if (a == 0) {
...
}
通过阅读 C99 和 C++11 标准的引用(在这篇文章的后面),我们发现 C99 明确地保证所有位设置为的整数类型0
将代表值0
在那种类型中。
我在 C++11 标准中找不到这种保证。
- 难道就没有这样的保证吗?
- 前面的代码片段的结果真的是特定于实现的吗?
在 C99 中(ISO/IEC 9899:1999)
5.2.1.2/1 多字节字符
所有位为零的字节应被解释为空字符
独立于移位状态。这样的字节不得作为任何字节的一部分出现
其他多字节字符。
6.2.6.2/1 整数类型
The values of any padding bits are unspecified.45) A valid
(non-trap) object representation of a signed integer type where the
sign bit is zero is a valid object representation of the corresponding
unsigned type, and shall represent the same value.
对于任意整数
类型,所有位都为零的对象表示应为
该类型中值零的表示。
在 C++11 中(ISO/IEC 14882:2011)
2.3/3 字符集 [lex.charset]
基本执行字符集和基本执行
宽字符集应包含基本字符集的所有成员
源字符集,加上表示警报的控制字符,
退格键和回车符,加上空字符(分别,
空宽字符),其表示全部为零位.
C++ 11
我认为相关的部分是
C++11 中的 3.9.1/1
对于字符类型,对象表示的所有位都参与
在值表示中。对于无符号字符类型,值表示的所有可能的位模式都表示数字。这些要求不适用于其他类型。
与 3.9.1/7 一起
整数类型的表示
应使用纯二进制计数系统定义值。
C11
6.2.6.2 非常明确
For unsigned integer types other than unsigned char, the bits of the object
representation shall be divided into two groups: value bits and padding bits (there need
not be any of the latter). If there are N value bits, each bit shall represent a different
power of 2 between 1 and 2N−1, so that objects of that type shall be capable of
representing values from 0 to 2N − 1 using a pure binary representation; this shall be
known as the value representation. The values of any padding bits are unspecified.
对于有符号整数类型,对象表示的位应分为三部分
组:值位、填充位和符号位。不需要任何填充位;
signed char 不应有任何填充位。必须只有一个符号位。
作为值位的每个位应与对象中的相同位具有相同的值
相应无符号类型的表示(如果有符号中有 M 个值位)
类型和 N 为无符号类型,则 M ≤ N)。如果符号位为零,则不会影响结果值。如果符号位为 1,则应在其中之一修改该值
以下方式:
— 符号位为 0 的对应值取反(符号和大小);
— the sign bit has the value −(2M) (two’s complement);
— the sign bit has the value −(2M − 1) (ones’ complement).
其中哪一个适用是实现定义的,符号位 1 的值是否适用也是由实现定义的
并且所有值位为零(对于前两个),或者符号位和所有值位为 1(对于补码),是陷阱表示或正常值。在符号和的情况下
大小和补码,如果该表示是正常值,则称为
负零。
Summmary
我认为这两个标准的意图是相同的。
char
, signed char
and unsigned char
让所有位都参与该值
其他整数类型可能有填充位不参与该值。其中错误的位模式可能意味着无效值。
解释是纯二进制表示,其定义在上面的 C11 引用中得到了扩展。
有两点可能不太清楚:
我会保守一点,假设两者都是肯定的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)