Search code examples
cintegerconstantsliterals

Why can't a hexadecimal integer constant be negative?


This table shows type is the first type in which the value can fit. Examining 0xFFFFFFF0 with gdb shows it to be an unsigned type:

(gdb) ptype 0xFFFFFFF0
type = unsigned int

But 0xFFFFFFF0 is -16 when interpreted as a signed integer so why can't it fit in the int type? Doing the same with a decimal input shows the desired type:

ptype -16
type = int

I also wanted to ask about this sentence in the same link above:

There are no negative integer constants. Expressions such as -1 apply the unary minus operator to the value represented by the constant, which may involve implicit type conversions.

So -1 = 0 -1 = -1, AKA a negative integer? I don't understand this sentence.


Solution

  • There are no negative integer constants in C.

    The grammar for integer constants is:

    • A decimal constant is a sequence of decimal digits not starting with 0 and with an optional suffix (u and/or l or ll in either order with any cases [uppercase or lowercase]).
    • An octal constant is a sequence of octal digits starting with 0 and an optional suffix.
    • A hexadecimal constant is 0x followed by a sequence of hexadecimal digits, with any cases.

    None of those have a minus sign. All integers constants in C are numerals with nonnegative values. Where a minus sign appears with a constant in C code, as in -34, it is two separate tokens: a unary negation operator followed by a constant.

    The goal of selecting a type for a constant is to select a type that can represent its value. As a hexadecimal numeral, the value of FFFFFFF016 is 4,294,967,280. If 0xFFFFFFF0 were made a 32-bit int, the value of that int would be −16 in two’s complement or some other values in one’s complement or sign-and-magnitude. It would not be 4,294,967,280. So a 32-bit int cannot represent the value of this numeral, so the compiler does not use a 32-bit int for the type.

    There are also no negative floating-point constants. Enumeration constants and character constants can be negative in some circumstances.