On 05/06/2012 11:10 PM, somenath wrote:
> Hi All,
>
> While browsing through the old article in this group I have come
> across one article by Chrish Torek.
> http://groups.google.com/group/gnu.g...7a0f655e96ce16
>
>
> In this article he said.
>
> "Finally, let me say one last time that the Standard C grammar DOES
> NOT use operator precedence. (At most, one can say that the grammar
> "implies" a precedence. I believe the word "specifies" is too
> strong, despite its appearance in a non-normative footnote."
>
> So the following expression
>
> 2+3*5;
> is equal to 17. For human * has higher precedence than + so *
> operator will be first operated on 3*5 and then the resultant will be
> added to 2. So the result will be 2+(3*5) .
>
> Then my question is how C compiler with out bothering about precedence
> produce the same result as 2+(3*5).
Without going into the details, let me state that 2, 3, and 5 all
qualify as "cast-expressions".
The relevant grammar rules are:
multiplicative-expression:
cast-expression
multiplicative-expression * cast-expression
additive-expression:
multiplicative-expression
additive-expression + multiplicative-expression
The parse tree is as follows (monospaced font required):
2 + 3 * 5
cast-expression + cast-expression * cast-expression
cast-expression +(multiplicative-expression * cast-expression)
multiplicative-expression + multiplicative-expression
(additive-expression + multiplicative-expression)
additive-expression
These grammar rules encode the equivalent of operator precedence in the
fact that the grammar rules for a additive expression require
multiplicative expressions as operands, whereas multiplicative
expressions do not allow additive expressions as operators. If the C
grammar followed a similar pattern for all of the operators, it would be
equally accurate to describe it in terms of precedence or grammar rules.
However, the grammar rules for the conditional expressions do not allow
for a simple precedence-based interpretation:
conditional-expression:
logical-OR-expression
logical-OR-expression ? expression : conditional-express
Any kind of expression can occur between the ? and the :, which would
imply that conditional expressions have the lowest possible precedence.
However, neither the first nor the third operand of a conditional
expression can be an assignment expression or a comma expression, which
would imply that it has higher precedence than assignment operators or
the comma operator.
--
James Kuyper