C++文本整数类型
C++ literal integer type
文字表达式也有类型吗?
long long int a = 2147483647+1 ;
long long int b = 2147483648+1 ;
std::cout << a << ',' << b ; // -2147483648,2147483649
是的,文字数字有类型。无后缀十进制整数文字的类型是int
、long
、long 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)
您可以在此处找到有关整数文本的详细信息。
相关文章:
- 将超出范围的整数分配给有符号字符类型
- 当我输入字符类型的数字时,为什么我无法获得整数?
- 整数类型应该显式转换(例如"int"到"无符号")还是只会增加混乱?
- 在 c++ 中,能够将浮点类型加 1 的最大整数是多少?
- 为什么 Clang 和 GCC 中两个无符号整数之和的结果类型不同
- 比较两个整数在C++中与未知 int 类型的相等性
- 如何在不给它任何类型(如整数)的情况下定义某物?
- 通过编译时值推断整数的类型
- C++/错误:表达式必须具有整数或无作用域枚举类型
- 从双精度转换为整数的显式类型是否始终检查整数溢出?
- 有没有办法将字符类型转换为整数?
- C++,概念不适用于无符号整数作为结果类型?
- 如何将整数分配给 char 类型的变量
- 类型转换问题:返回为整数而不是浮点/类型
- 涉及旧式枚举和整数类型的重载解析
- 将字符串转换为整数类型T,检查是否存在溢出
- 如何判断 c++ 向量中的值类型(整数或双精度)?
- 在 C/C++ 中,混合类型整数数学所需的最小类型向上转换是多少?
- 如何将字节数组转换为整数类型(整数、长整型、短型等)"安眠安"?
- 我可以在C++中制作一个强类型整数吗?