Friday, July 15, 2005

Precedence and associativity

For operators this two terms are very important ..Let me just go into the details of how these are interpretted

Precedence
3+4*5=35 or 23.

Associativity
45 - 45 -5 = -5 or 5

We can specify the precedence and associativity using %left,%right or %nonassoc followed by list of tokens.



All of the tokens on the same line have the same precedence level and associativity; the lines occur in order of increasing precedence. The following lines describe the precedence and associativity of the four arithmetic operators:

%left  '+'  '-'
%left '*' '/'


So as you can see ,in the previous example we can make the grammar by specifying the following in the definitions section.

%left '-'

Now when i compileandrun , i get ....

$./compileandrun.sh rpcalc.y
45 - 45 - 5
-5

0 Comments:

Post a Comment

<< Home