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. [...]
source share