【问题标题】:Why can integer type int64_t not hold this legal value? [duplicate]为什么整数类型 int64_t 不能保持这个合法值? [复制]
【发布时间】:2019-11-28 00:51:40
【问题描述】:

我正在尝试为某些极端情况编写测试用例。对于int64_t 类型的输入,以下行将无法编译:

int64_t a = -9223372036854775808LL;

错误/警告是:

error: integer constant is so large that it is unsigned [-Werror]

我认为这个数字超出了范围,所以我尝试了:

std::cout << std::numeric_limits<int64_t>::min() << std::endl;

它输出完全相同的数字!!!所以常数在范围内。

我该如何解决这个错误?

【问题讨论】:

    标签: c++ c++11 int int64 numeric-limits


    【解决方案1】:

    你可以写

    int64_t a = -1 - 9223372036854775807LL;
    

    问题在于- 不是文字的一部分,它是一元减号。所以编译器首先看到9223372036854775808LL(超出了有符号int64_t的范围),然后找到它的负数。

    通过应用二进制减号,我们可以使用两个在范围内的文字。

    【讨论】:

      【解决方案2】:

      Ben 已经解释了原因,这里有另外两个可能的解决方案。

      试试这个

      int64_t a = INT64_MIN;
      

      或者这个

      int64_t a = std::numeric_limits<int64_t>::min();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-07-22
        • 1970-01-01
        • 1970-01-01
        • 2018-08-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-02
        相关资源
        最近更新 更多