Home > other >  According to the C standard (or compilers), is a negative integer literal interpreted as single lite
According to the C standard (or compilers), is a negative integer literal interpreted as single lite

Time:08-19

(I don't know if this is is a topic covered in the C standard, or it's compiler-dependent; in the latter case, I'm interested about the general treatment).

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)?

CodePudding user response:

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…

CodePudding user response:

-16 is an operator - and an integer constant with value 16 and type int.


Try below. Even library constants are carefully constructed to avoid -0x80000000 which have the same value as (-0x7fffffff-1) but is a wider type as 0x80000000 is outside the int range.

#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
puts(TOSTRING(INT_MIN));

Output

(-0x7fffffff-1)

CodePudding user response:

It's a single literal. The token parser accepts an int with a regex like -?[^0]\d*.

  • Related