从一个例子
unsigned long x = 12345678UL
Run Code Online (Sandbox Code Playgroud)
我们总是知道编译器需要在上面的例子中只看到"long"来设置4个字节(32位)的内存.问题是为什么我们应该在长常量中使用L/UL,即使在声明它很长之后也是如此.
由于 C++20 二进制补码表示是标准允许的唯一表示,保证范围从 -2 N-1到 +2 N-1 -1。因此,对于 64 位有符号整数类型,范围从-9'223'372'036'854'775'808到9'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
}
Run Code Online (Sandbox Code Playgroud)
然而,如果我用long long x{-9'223'372'036'854'775'807LL - 1}compiles替换代码就好了并x保持正确的值。我没有得到什么?