C++文本整数类型

C++ literal integer type

本文关键字:类型 整数 文本 C++      更新时间:2023-10-16

文字表达式也有类型吗?

long long int a = 2147483647+1 ;
long long int b = 2147483648+1 ; 
std::cout << a << ',' << b ; // -2147483648,2147483649

是的,文字数字有类型。无后缀十进制整数文字的类型是intlonglong long中的第一个,其中整数可以表示。二进制、十六进制和八进制文本的类型选择类似,但列表中也包含无符号类型。

可以使用U后缀强制使用无符号类型。如果在后缀中使用单个L,则该类型将至少为long,但如果无法表示为long,则可能会long long。如果使用LL,则必须long long类型(除非实现具有比long long宽的扩展类型)。

结果是,如果int是 32 位类型,long是 64 位类型,则2147483647具有类型int,而2147483648具有类型long。这意味着2147483647+1将溢出(这是未定义的行为),而2147483648+1只是2147483649L

这由C++标准的§2.3.12([lex.icon])第2段定义,上述描述是该部分表7的摘要。

请务必记住,赋值的目标类型不会以任何方式影响赋值右侧表达式的值。如果你想强制一个计算有一个long long的结果,你需要强制计算的某个参数long long;仅仅分配给long long变量是不够的:

long long a = 2147483647 + 1LL;
std::cout << a << 'n';

生产

2147483648

(住在科利鲁)

int a = INT_MAX ;
long long int b = a + 1 ; // adds 1 to a and convert it then to long long ing
long long int c = a; ++c; // convert a to long long int and increment the result with 1
cout << a << std::endl; // 2147483647
cout << b << std::endl; // -2147483648
cout << c << std::endl; // 2147483648
cout << 2147483647 + 1 << std::endl; // -2147483648 (by default integer literal is assumed to be int)
cout << 2147483647LL + 1 << std::endl; // 2147483648 (force the the integer literal to be interpreted as a long long int)

您可以在此处找到有关整数文本的详细信息。