Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why there is no sign character in the syntax of constants?

Tags:

c

syntax

Why doesn't the standard include a sign character in the syntax of constants?

It is mentioning only digits and sign character is only present in exponents.

like image 311
Sabrina Avatar asked Dec 15 '22 00:12

Sabrina


2 Answers

The standard does not bother with the sign in front of numeric literals because it would be redundant.

The syntax already captures the sign as part of unary plus + and unary minus - operators. When you write

int a = -4;

the syntax of the right-hand side could be adequately described as a unary minus - expression with the operand of 4. This is the approach that the standard takes.

like image 170
Sergey Kalinichenko Avatar answered Apr 01 '23 23:04

Sergey Kalinichenko


If - were a part of the constant -2 then 4-2 would be a syntax error (since a token is always the longest possible sequence of characters). Also, the semantics of -2147483648 and - 2147483648 would be different (the first one would be an int and the second one a long, assuming int is 32 bits and long is longer). Both of those things would be confusing.

If the - is always an operator, the semantics of -2147483648 are sometimes a little unexpected, but the more common x-1 works as expected. So that's how most programming languages, including C, work.

like image 26
rici Avatar answered Apr 01 '23 23:04

rici