为什么256是一个signed char在C ++中未定义 [英] Why 256 for a signed char is undefined in C++
问题描述
阅读C ++ Primer第5版的书,我注意到一个 signed char
的值为 256
未定义。
我决定尝试,我看到 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++?
推荐答案
编辑:见下面TC的回答。更好。
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.
这篇关于为什么256是一个signed char在C ++中未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!