简体   繁体   中英

Trying to understand C Grammar

I started my journey into recursive parsers, and was looking into C Grammar, trying to understand how it works to replicate it in my code.

Then I saw this:

assignmentExpression
:   conditionalExpression
|   unaryExpression assignmentOperator assignmentExpression
|   DigitSequence // for
;

and this part in particular:

unaryExpression assignmentOperator assignmentExpression

With my (poor and probably wrong) understanding, a unary expression can be a Constant (if you follow the rest of the grammar), then it looks like this 1 = 1 is valid, which is obviously wrong. I searched for C parsers, even the GCC source code, and the assignmentExpression functions never really have any code related to the unaryExpression part.

So I'm really confused; I'm probably missing something very important here.

C is not completely described by its grammar; a valid C program must conform to the grammar, but it also must conform to many other rules, eg rules relating to the type system.

So, you're right: 1 = 1 conforms to the rule you've quoted, but it's invalid anyway, because the left-hand-side is not an lvalue.

(Note that some compilers may actually treat 1 = 1 as a syntax error, because they may roll some of these other restrictions into the grammar that they apply. That's allowed; the spec gives compilers a lot of flexibility in how they implement things, as long as they handle valid programs correctly.)

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