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


基础教程推荐
- 我有静态或动态 boost 库吗? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 常量变量在标题中不起作用 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01