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, or9. - An octal-constant starts with
0. - A hexadecimal-constant starts with
0xor0X.
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,
sizeofexpressions whose results are integer constants,_Alignofexpressions, and floating constants that are the immediate operands of casts…
CodePudding user response:
-16 is two tokens: an operator - and an integer constant with value 16 and type int.
Try below. Even library constants are carefully constructed to avoid -2147483648 which has the same value as (-0x7fffffff-1) but is a wider type as 2147483648 is outside the int range.
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
puts(TOSTRING(INT_MIN));
Output
(-0x7fffffff-1)
