昨天面试时被问到以下代码的输出
#include <stdio.h>
int main(void){
printf ("%x" ,-1<<4);
}
我有 2 分钟时间告诉我答案。我回复了 fffffff0
。面试结果尚未公布。我想知道我的答案是否正确?
最佳答案
从技术上讲,将负整数左移会调用未定义行为。这意味着 -1<<4
是UB。我不知道他们为什么问你这个问题。可能他们想测试您对 C 和 C++ 标准的了解程度。
C99 [ 6.5.7/4
] 说
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 通过 omitting the relevant text 使其行为未定义.
关于c++ - 面试题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4269838/