-2147483648
,例如,不是整数字面量。它是由一元运算符-
应用于字面量2147483648
的表达式。
在C++2011标准之前,C++不需要存在任何大于32位的类型(C++2011添加了至少64位的long long
),因此字面量2147483648
是不可移植的。
十进制整数字面量是以下第一个适合其值的类型:
int
long int
long long int (C++ 2011 and later)
请注意,在标准C++中,它从未是无符号类型。在C++标准的2011年之前的版本(没有
long long int
),一个十进制整数字面量如果太大而无法适应
long int
,则会导致未定义的行为 - 但您不太可能需要担心这个问题。在C++2011及以后的版本中,如果十进制整数字面量不适合
long long int
,则程序将是“非法的”。
一些非常旧的g ++版本没有实现C++2011语义。例如,g ++ 4.6.1(我基于原始版本回答此问题的版本)将文字
2147483648
视为
unsigned long
类型的常量。(有关更多过时信息,请参见此问题的编辑历史记录。)
以下是一个小程序,您可以使用它来显示编译器如何处理文字:
#include <iostream>
#include <climits>
const char *type_of(int) { return "int"; }
const char *type_of(unsigned int) { return "unsigned int"; }
const char *type_of(long) { return "long"; }
const char *type_of(unsigned long) { return "unsigned long"; }
const char *type_of(long long) { return "long long"; }
const char *type_of(unsigned long long) { return "unsigned long long"; }
int main()
{
std::cout << "int: " << INT_MIN << " .. " << INT_MAX << "\n";
std::cout << "long: " << LONG_MIN << " .. " << LONG_MAX << "\n";
std::cout << "long long: " << LLONG_MIN << " .. " << LLONG_MAX << "\n";
std::cout << "2147483647 is of type " << type_of(2147483647) << "\n";
std::cout << "2147483648 is of type " << type_of(2147483648) << "\n";
std::cout << "-2147483647 is of type " << type_of(-2147483647) << "\n";
std::cout << "-2147483648 is of type " << type_of(-2147483648) << "\n";
}
当我使用 g++ 11.3.0 在 64 位 Ubuntu 上编译并执行它时,我得到:
int: -2147483648 .. 2147483647
long: -9223372036854775808 .. 9223372036854775807
long long: -9223372036854775808 .. 9223372036854775807
2147483647 is of type int
2147483648 is of type long
-2147483647 is of type int
-2147483648 is of type long
std::cout
的流操作符可能不会按你所期望的那样提升这些字面值。 - AJG85numeric_limits<int>::min()
,而是使用硬编码字面量,这将是编译器默认使用的任何内容。 - AJG85numeric_limits
,以明确编译器使用的内容,而且他的值是正确的。 - Gunther Piez