为什么在 C++ 中未定义有符号字符的 256

2022-01-12 00:00:00 char signed c++

阅读 C++ Primer 5th edition book,我注意到一个值为 256signed char 是未定义的.我决定尝试一下,我发现 std::cout 不适用于该 char 变量.(无印刷).

Reading the C++ Primer 5th edition book, I noticed that a signed char with a value of 256 is undefined. I decided to try that, and I saw that std::cout didn't work for that char variable. (Printed Nothing).

但是在 C 上,同样的事情signed char c = 256;将为 char c 提供一个值 0.

But on C, the same thing signed char c = 256; would give a value 0 for the char c.

我尝试搜索但没有找到任何东西.

I tried searching but didn't find anything.

有人可以向我解释为什么在 C++ 中会出现这种情况吗?

Can someone explain to me why is this the case in C++?

我知道 256 是 2 个字节,但为什么 C++ 中的情况与 C 不同?

I understand that 256 is 2 bytes, but why doesn't the same thing as in C, happen to C++?

推荐答案

见下面 T.C. 的回答.这样更好.

See T.C.'s answer below. It's better.

有符号整数溢出在 C++ 和 C 中是未定义的.在大多数实现中,signed char 的最大值 SCHAR_MAX 为 127,因此将 256 放入其中会溢出它.大多数情况下,您会看到数字只是环绕(到 0),但这仍然是未定义的行为.

Signed integer overflow is undefined in C++ and C. In most implementations, the maximum value of signed char, SCHAR_MAX, is 127 and so putting 256 into it will overflow it. Most of the time you will see the number simply wrap around (to 0), but this is still undefined behavior.

相关文章