4 ms·
Doesn't list my favorite footgun. x and y are unsigned short. The expression `x*y` has defined behavior for... a) all values of x and y. b) some values of x
by leni536 4y ago
Doesn't list my favorite footgun.
x and y are unsigned short. The expression `x*y` has defined behavior for...
a) all values of x and y.
b) some values of x and y.
c) no values of x and y.
- deleted 4y ago[deleted]
- shultays 4y agoI am gonna say A but I guess I dont the foot gun here
- Veliladon 4y agoThe shorts are not promoted to ints (if you even declared the result as that type) until after the multiplication. The result will first be put into a short and then promoted to int. It's basically asking for an overflow error. Given that 256^2 is 65536 you don't have to be multiplying large numbers before hitting that overflow.
- loeg 4y agoUnsigned short has defined overflow, though.
- shultays 4y agoI don't follow, assuming short is half the size of int it would only overflow if most significant bits of both values are 1. Where did that 256^2 come from? It wouldn't overflow if a and b were 256 I missed that the result would be promoted to signed int, which only most significant bits are set
- deleted 4y ago[deleted]
- LegionMammal978 4y agoAll operands are always promoted to int (or unsigned int, long, unsigned long, etc.) before any operation. The footgun in this example is that even though you're using unsigned integers and would expect guaranteed wrapping semantics, the promotion to signed int makes it UB for USHORT_MAX*USHORT_MAX.
- jandrese 4y ago65536 * 65536 would overflow an int.
- shultays 4y agoAh I didn't know it would be promoted to signed int. Another thread here explains it as well. Thanks
- loeg 4y ago(B), assuming int is 32-bit and short is 16-bit. The multiplication promotes both operands and result to signed int, right? So if both x and y are uint16_max, the result overflows signed int and is UB, I think. But if int were larger (eg 64 bit) and short remained 16 bits, there’s no overflow and the answer is (A). I think.
- jstimpfle 4y agoThere was definitely a question that covered the auto-promotion to int, maybe with slightly different types.
- nayuki 4y agoIf short = 16 bits and int = 16 bits, then x and y will be promoted to unsigned int. Unsigned multiplication has wraparound behavior, so x*y will be defined for all values. If short = 16 bits and int = 32 bits (or heck even 17 bits), then x and y will be promoted to signed int. Signed multiplication overflow is undefined behavior, so x*y will be undefined for some values when x*y is too large. In particular, 0xFFFF * 0xFFFF = 0xFFFE_0001, which is larger than INT_MAX = 0x7FFF_FFFF. If short = 16 bits and int = 64 bits (or even 33 bits), then x and y will be promoted to signed int. The range of x*y will always fit int, so no overflow occurs, and the expression is defined for all input values. Isn't C fun?