Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why not C++ define INT_MIN as (1<<31)

I understand the reason why C++ define INT_MIN as (-2147483647 - 1), but why don't they just use 1<<31 ? That prevent the overflow and also easy to understand.

like image 931
Jun Avatar asked Dec 20 '22 04:12

Jun


1 Answers

That prevent the overflow and also easy to understand

How could it prevent the overflow, if by left-shifting a positive number you are trying to obtain a negative one? ;)

Keep in mind, that signed integer overflow is Undefined Behavior. Per paragraph 5.8/2 of the C++11 Standard:

The value of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are zero-filled. [...] Otherwise, if E1 has a signed type and non-negative value, and E1×2^E2 is representable in the corresponding unsigned type of the result type, then that value, converted to the result type, is the resulting value; otherwise, the behavior is undefined.

Also, per paragraph 5/4:

If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined. [...]

like image 66
Andy Prowl Avatar answered Dec 24 '22 01:12

Andy Prowl