c++ - 有符号到无符号转换,并返回,整数的定义行为?

标签 c++ c++11 integer type-conversion undefined-behavior

#include <cstdint>
#include <iostream>

int main() {
  uint32_t i = -64;
  int32_t j = i;

  std::cout << j;
  return 0;
}

我尝试过的大多数编译器都会创建输出 -64 的程序,但这是定义的行为吗?

  • 将有符号整数分配给无符号整数uint32_t i = -64;是否定义了行为?
  • 有符号整数赋值int32_t j = i;,当i等于4294967232时,定义了行为吗?

最佳答案

对于无符号整数越界转换,定义结果;对于有符号整数,它是实现定义的。

C++11(ISO/IEC 14882:2011) §4.7 Integral conversions [conv.integral/2]

If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2^n where n is the number of bits used to represent the unsigned type). [ Note: In a two’s complement representation, this conversion is conceptual and there is no change in the bit pattern (if there is no truncation). —end note ]

If the destination type is signed, the value is unchanged if it can be represented in the destination type (and bit-field width); otherwise, the value is implementation-defined.

此文本在 C++14 中保持不变。

关于c++ - 有符号到无符号转换,并返回,整数的定义行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18994563/

相关文章:

c++ - 为什么我得到一个 Expression is not assignable 错误

c++ - vector 中的模板推导失败

c++ - 如何防止时间戳被重新排序?

java - 如果字符已经是java中的数字,则将字符转换为整数

java - 将十六进制颜色字符串转换回整数

c++ - 为什么函数不给出整数溢出

c++ - Qt检查外部进程是否崩溃

c++ - Boost Log 初始化后设置 max_size

c++ - 无法初始化 constexpr

c - 在 C 中增量读取和写入长数据类型时出错