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 value2
rather than2.9
, becausex
is anint
andint
s 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 value42
(representing the character*
), rather than1066
, because there is nochar
with the value1066
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.