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?
Asked
Active
Viewed 269 times
1

Mason
- 501
- 3
- 11
-
The unary `-` is used in an expression. So `-128` applies the unary `-` to the decimal literal `128`, and gives a negative result. Since `128` has type `int`, so does `-128`. And since the `int` type is guaranteed to be able to represent any value in the range `-32767` to `32767`, there is no need for conversions. An `int` can represent `128` or `-128` - guaranteed. – Peter Nov 04 '19 at 06:06
-
@Peter Does it mean, that `int i = -2147483648;` requires a conversion with 32-bit `int`? UPDATE: It's discussed here: [How do I define a constant equal to -2147483648?](https://stackoverflow.com/q/27612996/580083). – Daniel Langr Nov 04 '19 at 06:27
1 Answers
1
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
).

JaMiT
- 14,422
- 4
- 15
- 31