Search code examples
cparsingcompilationnumericliterals

According to the C standard, is a negative integer literal interpreted as single literal, or operator and literal?


How are negative integers interpreted by the C standard/compilers - as a single literal, or as a (unary) operator and a numeric literal?

For example, is -16 interpreted a -16 or -(16)?


Solution

  • C 2018 6.4.4.1 1 shows the grammar for integer constants. It says an integer-constant is one of:

    • decimal-constant integer-suffixopt
    • octal-constant integer-suffixopt
    • hexadecimal-constant integer-suffixopt

    Since we are only interested in how these start, the integer-suffix does not concern us. The following grammar rules show:

    • A decimal-constant starts with a nonzero-digit, which is of course one of 1, 2, 3, 4, 5, 6, 7, 8, or 9.
    • An octal-constant starts with 0.
    • A hexadecimal-constant starts with 0x or 0X.

    Therefore, no integer-constant starts with - or +.

    -16 is parsed as the unary - operator followed by the integer constant 16. This forms an integer constant expression as specified in C 2018 6.6 6, which says:

    … An integer constant expression shall have integer type and shall only have operands that are integer constants, enumeration constants, character constants, sizeof expressions whose results are integer constants, _Alignof expressions, and floating constants that are the immediate operands of casts…