Why 256 for a signed char is undefined in C++(为什么在 C++ 中未定义有符号字符的 256)
问题描述
阅读 C++ Primer 5th edition book,我注意到一个值为 256
的 signed 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.
这篇关于为什么在 C++ 中未定义有符号字符的 256的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么在 C++ 中未定义有符号字符的 256


- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 从python回调到c++的选项 2022-11-16
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 静态初始化顺序失败 2022-01-01
- 近似搜索的工作原理 2021-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- C++ 协变模板 2021-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01