C++ 测试 - 符号位 1 是否总是表示负数?

标签 c++ number-formatting

我刚参加 C++ 测试,我答错了以下问题:

问:以下程序的输出是什么?

#include <iostream>
#include <stdint.h>

using namespace std;

int main() {
    int a = 0;
    for (int8_t i = 1; i > 0; i <<= 1)
        a++;
    cout << a;
    return 0;
}

有以下答案可供选择

  • 8
  • 7
  • 未定义的行为
  • 编译错误

正确”的答案是 7。如果答案中有“实现定义的行为”,我会选择它,所以我选择了最接近的未定义行为。我知道在符号和幅度、1 的补码和 2 的补码中,答案将是 7。但是 C++ 标准理论上不允许任何其他数字表示吗?例如符号和大小,但 0 表示负数?

我是否正确,这个问题的真正正确答案应该是实现定义的行为,如果不是,您能否解释一下为什么答案是 7 而不管实现如何?

我阅读了对该问题的评论,最初似乎 a 的类型是 char,这显然引起了很多关于是否 char 的提示。是否已签名,因此 testsetter 将其更改为 int8_t。作为奖励问题,是 <stdint.h> C++ 的一部分? O_O

最佳答案

出于不同的原因,我会说它是未定义的(而不是实现定义的)。

从 5.8:3 开始

The value of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are zero-filled. 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. Otherwise, if E1 has a signed type and non-negative value, and E1 × 2E2 is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.

关于C++ 测试 - 符号位 1 是否总是表示负数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15597198/

相关文章:

c++ - vector 的 vector 的初始化是否可以进行范围构造?

Javascript 从 NumberFormat 获取小数点和千位分隔符

asp.net-mvc - asp.net mvc 设置数字格式默认十进制千位分隔符

java - 自定义电话号码的正则表达式?

java - 如何获得与用户从 JFormattedTextField 看到的值相同的值?

c++ - 如何创建一个返回数组的函数

c++ - 将 OpenGL 用于 2D

PHP number_format 是否四舍五入?

c++ - 分配给引用参数会使对象无效

c++ - 逐字获取String Word的函数