Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the declaration affect the comma operator?

The following code doesn't compile.

int n;
int x=1, n++; //compiler error

error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘attribute’ before ‘++’ token

If we separate the declaration of x, the program compiles fine.

int n, x;
x=1, n++;//no error

Why is this so?

like image 915
AIB Avatar asked Dec 24 '22 15:12

AIB


2 Answers

x=1,n++;

is an expression statement, , here is the comma operator. However,

int x=1,n++;

is a declaration, not expression, , here is NOT interpreted as the comma operator.

C11 §6.7 Declarations

declaration:
    declaration-specifiers init-declarator-listopt ;
    static_assert-declaration

 declaration-specifiers:
    storage-class-specifier declaration-specifiersopt
    type-specifier declaration-specifiersopt
    type-qualifier declaration-specifiersopt
    function-specifier declaration-specifiersopt
    alignment-specifier declaration-specifiersopt

 init-declarator-list:
    init-declarator
    init-declarator-list , init-declarator  // comma

 init-declarator:
    declarator
    declarator = initializer

The comma in declaration is just a separator. Since n++ is not a valid init-declarator, the compiler reports an error.

like image 160
Yu Hao Avatar answered Dec 27 '22 05:12

Yu Hao


The comma in int x=1,n++; is not a comma operator, its a comma separator. n++ will be treated as another identifier but as per the rule, an identifier can't contain ++ , therefore compiler will raise error.
The only special character allowed in identifiers is underscore _.

C11: 6.4.2.1 (p2):

An identifier is a sequence of nondigit characters (including the underscore _, the lowercase and uppercase Latin letters, and other characters) and digits, which designates one or more entities as described in 6.2.1. Lowercase and uppercase letters are distinct. There is no specific limit on the maximum length of an identifier.

and para 4 says:

When preprocessing tokens are converted to tokens during translation phase 7, if a preprocessing token could be converted to either a keyword or an identifier, it is converted to a keyword.

n++ can't be converted to either a keyword or an identifier in the translation phase.

like image 26
haccks Avatar answered Dec 27 '22 05:12

haccks