Search code examples
c++charsigned

Why 256 for a signed char is undefined in C++


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).

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.

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

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


Solution

  • Edit: See T.C.'s answer below. It's better.

    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.