c – 对有符号整数类型的按位运算结果是否定义明确?

考虑以下代码
using integer = int; // or any other fundamental integral type
using unsigned_integer = typename std::make_unsigned<integer>::type;
constexpr integer bits = std::numeric_limits<unsigned_integer>::digits;
integer value = -42; // or any value
integer mask = static_cast<integer>(1)<<static_cast<integer>(bits-1);
bool result_and = value & mask;
bool result_or = value | mask;
bool result_xor = value ^ mask;

我想知道根据标准定义的这些操作有多好.我是否有保证在所有架构上获得相同的结果?我肯定会对所有架构上的符号位进行操作,这个符号位为0表示正数,1表示负数?

解决方法

按位和按位或按位xor的结果目前在标准中未指定,特别是从未定义了按位这一术语.我们有 defect report 1857: Additional questions about bits 涵盖了这个问题并说:

The specification of the bitwise operations in 5.11 [expr.bit.and],
5.12 [expr.xor],and 5.13 [expr.or] uses the undefined term “bitwise” in describing the operations,without specifying whether it is the
value or object representation that is in view.

Part of the resolution of this might be to define “bit” (which is otherwise currently undefined in C++) as a value of a given power of 2.

决议是:

CWG decided to reformulate the description of the operations
themselves to avoid references to bits,splitting off the larger
questions of defining “bit” and the like to issue 1943 for further
consideration.

这导致合并defect report 1943: Unspecified meaning of “bit”.

左移有符号类型的结果将取决于底层表示.我们可以从defect report 1457: Undefined behavior in left-shift看到这一点,这使它很好地定义为左移到符号位并说:

The current wording of 5.8 [expr.shift] paragraph 2 makes it undefined
behavior to create the most-negative integer of a given type by
left-shifting a (signed) 1 into the sign bit,even though this is not
uncommonly done and works correctly on the majority of
(twos-complement) architectures
:

…if E1 has a signed type and non-negative value,and E1 ⨯ 2E2 is representable in the result type,then that is the resulting value;
otherwise,the behavior is undefined.


结果,这种技术不能用于常量表达,
这将打破大量的代码.

注意到对声明的强调在大多数情况下都能正常工作(二次补充)架构.所以它依赖于底层表示,例如二进制补码.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...