Interview Question

Technically left-shifting a negative integer invokes Undefined Behaviour. That means -1<<4 is UB. I dont know why they asked you this question. Probably they wanted to test your depth of knowledge of the C and C++ Standards.

C99 [6.5.7/4] says

The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled with zeros. If E1 has an unsigned type, the value of the result is E1× 2E2, reduced modulo
one more than the maximum value representable in the result type. If E1 has a signed
type and nonnegative value, and E1× 2E2 is representable in the result type, then that is
the resulting value; otherwise, the behavior is undefined.

C++03 makes it undefined behaviour by omitting the relevant text.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)