C ++文字整数类型 [英] C++ literal integer type
问题描述
文字表达式也有类型吗?
Do literal expressions have types too ?
long long int a = 2147483647+1 ;
long long int b = 2147483648+1 ;
std::cout << a << ',' << b ; // -2147483648,2147483649
推荐答案
是的,字面数字有类型。未加十进制整数文字的类型是 int
中的第一个, long
, long long
,其中可以表示整数。类似地选择二进制,十六进制和八进制文字的类型,但列表中也使用无符号类型。
Yes, literal numbers have types. The type of an unsuffixed decimal integer literal is the first of int
, long
, long long
in which the integer can be represented. The type of binary, hex and octal literals is selected similarly but with unsigned types in the list as well.
您可以使用<$强制使用无符号类型c $ c> U 后缀。如果在后缀中使用单个 L
,则类型将至少 long
但它可能 long long
如果它不能表示为 long
。如果你使用 LL
,那么类型必须是 long long
。
You can force the use of unsigned types by using a U
suffix. If you use a single L
in the suffix then the type will be at least long
but it might be long long
if it cannot be represented as a long
. If you use LL
, then the type must be long long
.
结果是,如果 int
是32位类型而 long
是64位,那么 2147483647
的类型为 int
,而 2147483648
的类型为长
。这意味着 2147483647 + 1
将溢出(这是未定义的行为),而 2147483648 + 1
只是 2147483649L
。
The consequence is that if int
is a 32-bit type and long
is 64 bits, then 2147483647
has type int
while 2147483648
has type long
. That means that 2147483647+1
will overflow (which is undefined behaviour), while 2147483648+1
is simply 2147483649L
.
这是由§ 2.3.12( [lex.icon]
)C ++标准的第2段,以上描述是该部分表7的摘要。
This is defined by §2.3.12 ([lex.icon]
) paragraph 2 of the C++ standard, and the above description is a summary of Table 7 from that section.
重要的是要记住类型赋值的目的地不会以任何方式影响赋值右侧的表达式的值。如果你想强制计算得到 long long
结果,你需要强制计算的一些参数为 long long
;只分配到 long long
变量是不够的:
It's important to remember that the type of the destination of the assignment does not influence in any way the value of the expression on the right-hand side of the assignment. If you want to force a computation to have a long long
result you need to force some argument of the computation to be long long
; just assigning to a long long
variable isn't enough:
long long a = 2147483647 + 1LL;
std::cout << a << '\n';
产生
2147483648
这篇关于C ++文字整数类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!