编程原理与实践第 2 版。签名字符溢出

Programming principles and practice 2nd ed. signed char overflow

我已经完成了 C++ 入门第 5 版,现在我正在阅读 Strostrup 撰写的 C++ 编程原理和实践第 2 版。然而,作者在很多情况下似乎依赖于一些 UB,例如:

 int x = 2.9;
 char c = 1066;

Here x will get the value 2 rather than 2.9 , because x is an int and ints don’t have values that are fractions of an integer, just whole integers (obviously). Similarly, if we use the common ASCII character set, c will get the value 42 (representing the character * ), rather than 1066, because there is no char with the value 1066 in that character set.

但是 char x = 1066; 溢出 signed char 所以行为是未定义的,我不确定他在说什么:它产生 * 因为 UB 可以表示任何东西我想因此我们不依赖甚至猜测结果。所以你怎么看?谢谢!

But char x = 1066; is overflowing a signed char so the behavior is undefined

这不是真的。

溢出是算术运算的结果。这里发生的是转换。将不可表示的整数转换为另一种整数类型不会有未定义的行为,即使该类型是有符号的。

P.S。 char 不是 signed char。它们是不同的类型。它的实现定义了 char 是有符号的还是无符号的。