简体   繁体   English

一元减号运算符如何与 C++ 中的 integer 文字一起使用?

[英]How the unary minus operator works with integer literals in C++?

I read that decimal literals are signed by default.我读到十进制文字是默认签名的。
For simplicity, assume that the values that int can hold are the integers [-128,127], and long can hold the integer 128. Now, what happens if I code the literal -128?为简单起见,假设int可以容纳的值是整数 [-128,127],而long可以容纳 integer 128。现在,如果我对文字 -128 进行编码会发生什么? What I know is that the literal here is simply '128', which can't fit into an int but rather would go into a long ?我所知道的是这里的文字只是'128',它不能适合int而是 go 适合long吗? or does the unary minus operator do something else?还是一元减号运算符做其他事情?
So, how does the unary minus sign work with integer literals?那么,一元减号如何与 integer 文字一起使用?

From cppreference.com :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. integer 文字的类型是该值可以适合的第一种类型,来自类型列表,这取决于使用的数字基数和整数后缀

When using a decimal base and no suffix, as in your example, the possible types are int , long int , and long long int .如您的示例所示,使用十进制基数且无后缀时,可能的类型为intlong intlong long int If the value (ignoring the minus sign) fits in a long but not in an int , then the type of the value is long .如果值(忽略减号)适合long但不适合int ,则值的类型是long

After the type is determined, the unary minus operator is applied as normal.确定类型后,将照常应用一元减号运算符。 Applying unary minus to a long results in a long (even if the result could fit in an int ).将一元减号应用于long会导致long (即使结果可能适合int )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM