[英]C grammar generates invalid expression
I am reading a book namad A Retargetable C Compiler: Design and Implementation.我正在读一本书 namad A Retargetable C Compiler: Design and Implementation。 In this book, the C language grammar is specified like this:
在本书中,C语言语法是这样规定的:
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
.我把
unary-expression assign-operator assignment-expression
作为assignment-expression
。
I choose "sizeof '(' type-name ')'"
for the unary-expression.我为一元表达式选择
"sizeof '(' type-name ')'"
。
Then I choose "="
for the assign-operator.然后我选择
"="
作为赋值运算符。
Then I chose "conditional-expression"
for the assignment-expression.然后我为赋值表达式选择了
"conditional-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"
.作为上述所有的结果,我可以生成这样的表达式:
"sizeof(int) = 7"
。
But this expression is not possible in C language.但是这个表达式在C语言中是不可能的。 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.表达式
sizeof(int) = 7
在语法上可能是正确的,但它没有多大意义。 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
.所以你的编译器而不是溢出
error: syntax error
将正确标记和解释语句并告诉你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 .关于这个话题,您可能对C11 标准草案中的附录 A.1 词法语法感兴趣。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.