c++ - - 9'223' 37 2'036' 85 4'775' 808LL 未签名

标签 c++ integer literals c++20 long-long

由于 C++20 二进制补码表示是标准允许的唯一表示,保证范围从 -2N-1 到 +2N-1-1。因此,对于 64 位有符号整数类型,范围从 -9'223'372'036'854'775'8089'223'372'036'854'775'807 .但是,此代码不能在 Visual Studio 上编译(也不能在 gcc 上编译)

int main()
{
    long long x{-9'223'372'036'854'775'808LL};
    // error C4146: unary minus operator applied to unsigned type, result still unsigned
    // error C2397: conversion from 'unsigned __int64' to '__int64' requires a narrowing conversion
}

然而,如果我用 long long x{-9'223'372'036'854'775'807LL - 1} 替换代码编译得很好,x保持正确的值。我没有得到什么?

最佳答案

没有 LL后缀类型作为符合标准的列表中的第一个类型。如果您使用 LL后缀,则该值将特别具有类型 long long .然而无论哪种方式9'223'372'036'854'775'808太大而无法放入 long long (这是最大的有符号类型)所以一些编译器允许它作为扩展成为 unsigned long long ,因此警告。 GCC 和 Clang do actually warn in that case .与许多人的看法相反, C 或 C++ 中没有负整数文字 . -9'223'372'036'854'775'808是应用于整数 9'223'372'036'854'775'808 的一元减号

The type of the literal

The type of the integer literal is the first type in which the value can fit, from the list of types which depends on which numeric base and which integer-suffix was used.

  • no suffix
  • decimal bases:
    • int
    • long int
    • long long int (since C++11)
  • binary, octal, or hexadecimal bases:
    • int
    • unsigned int
    • long int
    • unsigned long int
    • long long int (since C++11)
    • unsigned long long int (since C++11)
  • ...
  • suffix: ll or LL
  • decimal bases:
    • long long int (since C++11)
  • binary, octal, or hexadecimal bases
    • long long int
    • unsigned long long int (since C++11)
  • ...

If the value of the integer literal is too big to fit in any of the types allowed by suffix/base combination and the compiler supports extended integer types (such as __int128) the literal may be given the extended integer type -- otherwise the program is ill-formed.


其实以前有很多类似的问题在哪里 -2147483648也未签名 因为当时long long不在 C 和 C++ 标准中,最大的类型是 unsigned long :
  • Why do we define INT_MIN as -INT_MAX - 1?
  • (-2147483648> 0) returns true in C++?
  • Why does the smallest int, −2147483648, have type 'long'?
  • Why is 0 < -0x80000000?
  • Why does MSVC pick a long long as the type for -2147483648?
  • C: Casting minimum 32-bit integer (-2147483648) to float gives positive number (2147483648.0)
  • 关于c++ - - 9'223' 37 2'036' 85 4'775' 808LL 未签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61290255/

    相关文章:

    struct - 嵌套结构初始化文字

    java - 为什么 String 是 Java 中唯一存在文字的类?

    c++ - 设计算法的通用选项

    python - 在 Python 中取 int 的 2 次方模数的首选方法是什么

    c++ - 管理 cmake 依赖 git 模块

    Scala - 正整数之和为负 - 溢出异常?

    c++ - 如果我们在需要整数的 switch case 中输入一个字符会发生什么

    javascript - 什么时候应该在 javascript 中使用 === 或 ==、!== 和 != 等?

    c++ - 包含通过引用修改值的 lambda 的结构

    c++ - std::getline() 将回车符\r 读取到字符串中,如何避免这种情况?