Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
89 views
in Technique[技术] by (71.8m points)

c++ - Interview Question

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?

question from:https://stackoverflow.com/questions/4269838/interview-question

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 ?lled 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 unde?ned.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...