Reputation: 501
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? 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
! or does the unary minus operator do something else?
So, how does the unary minus sign work with integer literals?
Upvotes: 1
Views: 304
Reputation: 17072
From 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.
When using a decimal base and no suffix, as in your example, the possible types are int
, long int
, and long 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
.
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
).
Upvotes: 1