一元减号运算符如何与 C++ 中的整数文字一起使用?
How the unary minus operator works with integer literals in C++?
我了解到默认情况下十进制文字是有符号的。
为简单起见,假设 int
可以容纳的值是整数 [-128,127],而 long
可以容纳整数 128。现在,如果我编写文字 -128 会发生什么情况?我所知道的是,这里的文字只是“128”,它不能放入 int
中,而是可以放入 long
中!还是一元减号运算符做其他事情?
那么,一元减号如何与整数文字一起使用?
来自 cppreference.com:
The type of the integer literal is the first type in which the value can fit, from the list of types which depends on which numeric base and which integer-suffix was used.
当使用十进制基数且没有后缀时,如您的示例所示,可能的类型为 int
、long int
和 long long int
。如果值(忽略减号)适合 long
但不适合 int
,则值的类型为 long
.
确定类型后,将正常应用一元减号运算符。将一元减号应用于 long
会导致 long
(即使结果适合 int
)。
我了解到默认情况下十进制文字是有符号的。
为简单起见,假设 int
可以容纳的值是整数 [-128,127],而 long
可以容纳整数 128。现在,如果我编写文字 -128 会发生什么情况?我所知道的是,这里的文字只是“128”,它不能放入 int
中,而是可以放入 long
中!还是一元减号运算符做其他事情?
那么,一元减号如何与整数文字一起使用?
来自 cppreference.com:
The type of the integer literal is the first type in which the value can fit, from the list of types which depends on which numeric base and which integer-suffix was used.
当使用十进制基数且没有后缀时,如您的示例所示,可能的类型为 int
、long int
和 long long int
。如果值(忽略减号)适合 long
但不适合 int
,则值的类型为 long
.
确定类型后,将正常应用一元减号运算符。将一元减号应用于 long
会导致 long
(即使结果适合 int
)。