Tiago Oliveira
Tiago Oliveira

Reputation: 158

Is it normal for some C expressions allowed in its grammar, not to be allowed when compiled in practice?

I was studying the C grammar: http://www.quut.com/c/ANSI-C-grammar-y-1999.html#unary-expression

There's this rule

assignment_expression
: conditional_expression
| unary_expression assignment_operator assignment_expression
;

And

unary_expression
: postfix_expression
| INC_OP unary_expression
| DEC_OP unary_expression
| unary_operator cast_expression
| SIZEOF unary_expression
| SIZEOF '(' type_name ')'
;

So why can't we do something like:

++v = 3<4 ? 10 : 2;

since ++v is an unary_expression?

Upvotes: 1

Views: 69

Answers (2)

John Bode
John Bode

Reputation: 123468

The language grammar is only one part of the language definition. There are additional semantic rules and constraints that specify what syntax alone cannot. For example, syntax alone cannot specify that variables and functions must be declared before use, or that the operand of the unary * operator must have a pointer type, etc.

There is a constraint on assignment expressions that the target of an assignment must be a modifiable lvalue, which is an expression that specifies a region of memory such that the contents of that region may be read or updated. If v is the name of a variable, then it also serves as an lvalue.

However, the semantic rules of the ++ operator state that the result of ++v is not an lvalue, and as such cannot be the target of an assignment.

For chapter and verse on all of this, refer to the C 2011 online draft, sections 6.3.2.1 (Lvalues, arrays, and function designators), 6.5.3 (Unary operators), and 6.5.16 (Assignment operators).

Upvotes: 1

Eric Postpischil
Eric Postpischil

Reputation: 222724

Yes, it is normal. The C language is specified by several layers of rules. Roughly speaking, as an introduction:

  • Individual characters are gathered into preprocessing tokens according to C’s lexical rules.
  • The grammar specifies what sequences of preprocessing tokens are allowed as well as something of how they are interpreted (structured into a tree form).
  • Constraints specified in the C standard add semantic rules that the grammar is incapable of specifying. For example, a constraint on the assignment operator is that it shall have a modifiable lvalue as its left operand.
  • Additional rules in the C standard specify semantics and additional requirements.

Upvotes: 3

Related Questions