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

I understand why C ++ defines INT_MIN as (-2147483647 - 1), but why don't they just use 1 <31? This prevents overflow and is also easy to understand.

+4
source share
2 answers

This will prevent overflow, and also easy to understand.

How could this prevent overflow if you try to get a negative number by shifting to the left ?;)

Keep in mind that signed integer overflow is Undefined Behavior. In clause 5.8 / 2 of the C ++ 11 standard:

The value of E1 << E2 is E1 left-shifted position of E2 ; freed bits are filled with zeros. [...] Otherwise, if E1 has a signed type and a non-negative value, and E1Γ—2^E2 is representable in the corresponding unsigned type of the result type, then this value converted to the result type is the final value; , undefined behavior .

In addition, in paragraph 5/4:

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

+7
source

Because 1 << 31 causes undefined behavior (assuming a 32-bit int ).

+4
source

Source: https://habr.com/ru/post/1484049/


All Articles