Home > Back-end >  Programming principles and practice 2nd ed. signed char overflow
Programming principles and practice 2nd ed. signed char overflow

Time:11-28

I've finished C primer 5th edition and now I'm reading C programming principles and practice 2nd edition by Strostrup. However the author seems to depend on some UBs in many cases like this one:

 int x = 2.9;
 char c = 1066;

Here x will get the value 2 rather than 2.9 , because x is an int and ints don’t have values that are fractions of an integer, just whole integers (obviously). Similarly, if we use the common ASCII character set, c will get the value 42 (representing the character * ), rather than 1066, because there is no char with the value 1066 in that character set.

But char x = 1066; is overflowing a signed char so the behavior is undefined and I'm not sure about what he is saying: it produces * because a UB can mean anything as I guess thus we don't depend or even guess the results. So what do you think? Thank you!

CodePudding user response:

But char x = 1066; is overflowing a signed char so the behavior is undefined

That's not true.

Overflow happens as a result of an arithmetic operation. What happens here is conversion. Converting an unrepresentable integer to another integer type does not have undefined behaviour even if the type is signed.

P.S. char is not signed char. They are distinct types. It's implementation defined whether char is signed or unsigned.

  • Related