1

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?

  • 1
    The formal grammar doesn't define the language fully. There is a small set of additional requiremens written in English. – n. m. could be an AI Apr 07 '19 at 17:10
  • You are right. Those rules allow `++v =`. But see the note at the beginning of the file: _"I want to keep this version as close to the 1999 Standard C grammar as possible.._" which indicates it may not be a proper parser for the C language. – Paul Ogilvie Apr 07 '19 at 17:11

2 Answers2

3

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.
Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
1

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

John Bode
  • 119,563
  • 19
  • 122
  • 198