简体   繁体   中英

C grammar generates invalid expression

I am reading a book namad A Retargetable C Compiler: Design and Implementation. In this book, the C language grammar is specified like this:

expression:
  assignment-expression { , assignment-expression }
assignment-expression:
  conditional-expression
  unary-expression assign-operator assignment-expression
assign-operator:
  one of= += -= *= /= %= <<= >>= &= A= I=
conditional-expression:
  binary-expression [ ? expression : conditional-expression ]
binary-expression:
  unary-expression { binary-operator unary-expression }
binary-operator:
  one of || && '|' A & == ! = < > <= >= << >> + - * | %
unary-expression:
  postfix-expression
  unary-opera tor unary-expression
  '(' type-name ')' unary-expression
  sizeof unary-expression
  sizeof '(' type-name ')'
unary-operator:
  one of ++ -- & * + - - !
postfix-expression:
  primary-expression { postfix-operator }
postfix-operator:
  '[' expression ']'
  '(' [ assignment-expression { , assignment-expression } ] ')'
. identifier
-> identifier
++
--
primary-expression:
  identifier
  constant
  string-literal
  '(' expression ')'

I have a question about something I observed with:

expression:
    assignment-expression

I put unary-expression assign-operator assignment-expression for the assignment-expression .

I choose "sizeof '(' type-name ')'" for the unary-expression.

Then I choose "=" for the assign-operator.

Then I chose "conditional-expression" for the assignment-expression.

Then I derive like this:

conditional-expression -> binary-expression -> unary-expression ->postfix-expression -> primary-expression -> identifier

As a result of all the above, I can generate an expression like this: "sizeof(int) = 7" .

But this expression is not possible in C language. Is there a problem with the above grammar listing, or am I producing this expression in the wrong way?

That something is grammatically correct doesn't mean it is logically correct. The expression sizeof(int) = 7 may be grammatically correct, but it doesn't make much sense. So your compiler instead of spilling error: syntax error will tokenize and interpret the statement properly and tell you error: cannot assign to result of sizeof .

On the topic you may be interested in the Annex A.1 Lexical grammar in C11 standard draft .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM