c++ - 面试题

标签 c++ c

昨天面试时被问到以下代码的输出

#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/

相关文章:

c - 为什么开关不能按程序工作?

c - C 数组中的最小值、最大值和位置

c 使用 fstat 问题比较文件大小

c++ - Sleep() 是一个糟糕的设计,但似乎是我唯一的选择

c++ - 我怎样才能打印出同一列的值完全齐平的矩阵?

c++ - 为什么在 CentOS 7 上选择了错误的 GCC 7.2 libstdc++ ABI?

c++ - 使用递归的数组总和中的错误(编译和运行时)

c++ - RegQueryValueEx 不适用于发布版本,但在调试版本中工作正常

c - 将多个参数传递给 main()

c - 从 log1pf() 计算 asinhf() 的最准确方法?