by OMGWTF · 10y ago · 0 comments
unsigned int i = 16;
return (((((i >= i) << i) >> i) <= i));
? (I changed `int` to `unsigned int`.)In section J.2 Undefined Behaviour, the standard mentions that it's undefined when "an expression is shifted by a negative number or by an amount greater than or equal to the width of the promoted expression"
[1] http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
It's basically a question about knowing when you'll get burned by the size of int varying.
(i >= i) // 1
((i >= i) << i) // 0x10000 or 0
(((i >= i) << i) >> i) // 1 or 0
(((((i >= i) << i) >> i) <= i)) // ((0 or 1) <= 16) == 1
Where did I go wrong?UB.
> If the value of the right operand is negative
> or is greater than or equal to the width of
> the promoted left operand, the behavior is
> undefined"
(http://www.open-std.org/jtc1/sc22/WG14/www/docs/n1570.pdf - ISO/IEC 9899:201x (C11 Working Draft N1570): 6.5.7 Bitwise shift operators)Why would you bit-shift the result of a logical comparison?
This code makes no sense, it's wrong, and should be rewritten.