dexter
dexter

Reputation: 195

Why does -32768 have type signed long in the following platform?

Suppose that on a platform, the minimal signed value is −2^15 = −32768 and the maximum value is 2^15 −1 = 32767. The constant 32768 then doesn’t fit into signed and is thus signed long. As a consequence, the expression -32768 has type signed long. Thus the minimal value of the type signed on such a platform cannot be written as a literal constant.

From Modern C by Jens Gustedt.

It's trivial to understand why 32768 is signed long, but why is -32768 also signed long and not signed, given the minimum signed value of -32768?

Upvotes: 2

Views: 240

Answers (3)

dbush
dbush

Reputation: 224377

-32768 is not actually an integer literal. It's the integer literal 32768 with the unary - operator applied to it.

Since on this system the value 32768 is outside the range of int, the constant 32768 has type long. Applying the unary - to a value of type long results in an expression of type long, therefore -32768 has type long.

A way to get the value -32768 with type int, the proper expression would be -32767 - 1. The integer constant 32767 has type int. Applying the unary - operator to it still gives us a value in the range of int, then subtracting 1 gives us an expression of type int with value -32768.

Upvotes: 2

DevSolar
DevSolar

Reputation: 70333

Because -32768 is the positive literal 32768 (which does not fit into a 16-bit value and therefore must be represented by the next larger type), to which then the unary minus is applied (which does not change the type).

If you write e.g. ( ( - 32767 ) - 1 ), you get your constant in int type.

Upvotes: 3

phuclv
phuclv

Reputation: 41922

If int is a 16-bit type in your platform then 32768 doesn't fit in it. Therefore 32768 must have the next larger type which is long. -32768 isn't a negative integer literal but a unary minus applied to the literal 32768. Since 32768 is long, so is -32768

This is exactly the same as

Upvotes: 2

Related Questions