CS5031 Exercises 3: Grammars for Expressions

1. In ANSI-C, assuming a=1 and b=2, what are the values of a, b and c after each of the following, and explain why:

a) a++, b++, c=a+b;
b) c= a+ ++b;
c) c= a++ +b;
d) c= a+++b;
e) c= a++ + ++b;
f) c= a+++++b;

2. In ANSI-C, what is the parse tree for, and value of, each of:

a) 1 + (2 + 3);
b) (1 + 2) + 3;
c) 1 + 2 + 3;

3. In ANSI-C, what is the parse tree for, and value of, each of:

a) 1 - (2 - 3);
b) (1 - 2) - 3;
c) 1 - 2 - 3;

4. Assuming that ^ means raising to a power (e.g. 3^4 = 3*3*3*3 = 81 = 0x51), what is the parse tree for, and hexadecimal value of, each of:

a) 2 ^ (3 ^ 3)
b) (2 ^ 3) ^ 3
c) 2 ^ (3 * 3)
d) 2 ^ 3 ^ 3

5. In ANSI-C, what is the parse tree for, and value of, each of:

a) (1 + 2) * (3 + 4);
b) 1 + (2 * 3) + 4;
c) ((1 + 2) * 3) + 4;
d) 1 + 2 * 3 + 4;

6. Assuming an input expression "1-2-3", what parse tree is produced by each of the following Yacc grammars:

a) exp : number | number '-' number ;
b) exp : number | exp '-' number ;
c) exp : number | number '-' exp ;

7. Assuming an input expression "1+2*3+4", what parse tree is produced by each of the following Yacc grammars, assuming number is as defined in the example in the lectures:

a) exp : number | number '+' number | number '*' number ;
b) exp : term | exp '+' term ;
   term : number | term '*' number ;
c) exp : term | exp '*' term ;
   term : number | term '+' number ;
d) exp : number | exp '+' number | exp '*' number
e) exp : number | exp '+' exp | exp '*' exp ;

8. We used this lex pattern to recognise numbers: [0-9]+
What is the equivalent BNF, if we use yacc to recognise numbers?