Answers to 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	b	c
a) a++, b++, c=a+b;	2	3	5
b) c= a+ ++b;		1	3	4
c) c= a++ +b;		2	2	3
d) c= a+++b;		as (c)
e) c= a++ + ++b;	2	3	4
f) c= a+++++b;		illegal

The compiler's lexical analyser will try to recognise "++" and "+" operators before handing them over to its syntactic analyser, so it just dumbly tries to piece together as many "++" operators as it can (lex always tries to recognise the longest string it can). The syntactic analyser doesn't have a chance to make sense of "+++++", even though its only legal meaning is "++ + ++", as the lexical analyser has already recognised it as "++ ++ +" which is illegal in C. For similar reasons, (d) is treated as being the same as (c).

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;		as (b)

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

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

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)		2 ^ 27 = 0x8000000
b) (2 ^ 3) ^ 3		2 ^ 9 = 0x200
c) 2 ^ (3 * 3)		2 ^ 9 = 0x200
d) 2 ^ 3 ^ 3		as (a)

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

a) (1 + 2) * (3 + 4);	21
b) 1 + (2 * 3) + 4;	11
c) ((1 + 2) * 3) + 4;	13
d) 1 + 2 * 3 + 4;	as (b) = (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 ;	stops after 1-2
b) exp : number | exp '-' number ;	as 3b
c) exp : number | number '-' exp ;	as 3a

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 ;	stops after 1+2
b) exp : term | exp '+' term ;					as 5b
   term : number | term '*' number ;
c) exp : term | exp '*' term ;					as 5a
   term : number | term '+' number ;
d) exp : number | exp '+' number | exp '*' number		as 5c
e) exp : number | exp '+' exp | exp '*' exp ;			ambiguous, so unusable

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

number : digit | number digit ;
digit : '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | '0' ;