Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interview Question

Tags:

c++

c

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?

like image 577
Girish Mittal Avatar asked Nov 24 '10 17:11

Girish Mittal


2 Answers

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.

like image 183
Prasoon Saurav Avatar answered Oct 04 '22 03:10

Prasoon Saurav


No. You're not correct. That's the bad news. Good news is that the interviewer probably doesn't know that and will assume you are because it's the result THEY get when they compile and run it.

True answer is that it is implementation defined. I'm not 100% confident to say it IS undefined behavior because of the overload, but I think it may be. At the very least though the result is dependent upon how negative numbers are represented, etc... Neither language you've claimed this is in define what the output will be.

like image 33
Edward Strange Avatar answered Oct 04 '22 02:10

Edward Strange