Alex Rivera | Logout

Interview Question

Asked 2010-11-24T17:44:33.373
34

I was asked the output of the following code in my interview yesterday

#include <stdio.h>
int main(void){
       printf ("%x" ,-1<<4); 
}

I was given 2 minutes to tell the answer. I responded fffffff0. The result of the interview has not been declared yet. I want to know was my answer correct?

c++ c
Edit
Report

1 Answer

57

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.

answered 2010-11-24T17:47:51.263

Your Answer