=========================preview======================
(COMP251)COMP251_01F-mid_sol.pdf
Back to COMP251 Login to download
======================================================
COMP251 Fall 2001 Mid-term Exam Solution
Problem 1
1.
A BNF is ambiguous if there is a string in its language that can be generated by more than one parse trees. It is not desirable because in general, parse trees are used to define the semantics of the language, and when a string has more than one parse trees, its meaning will then be ambiguous. (common mistake: instead of a string, quite a few said that the *language* has more than one parse trees - a parse tree generate a string, not a language which is a set of strings.)
2.
It's good because it will then be easier to understand the flow of the program from the program source code. This will in turn make the program easier to read, maintain, and debug. It will also facilitate the verification of the programs using conditions attaching to these (entry and exit) points.
3.
The restriction is that the lower and upper bound of the index must be known at the compile time, i.e. they must be constants.
Problem 2
They do not always have the same behaviour. In particular, if S changes the value of i, the two programs may not have the same behaviour.
For Example, let S be the follwing statement:
i = 0;
Then the second program will just execute S twice and come to an end,but the first one will go into an infinite loop.
Problems 3-5:
The following codes are in C++-like syntex
//---------------------------------------------------------------Problem 3
void f(int x) {x = x + 1;}
void main()
{ int y = 2;
f(y); //CBV: y=2
//CBR: y=3
}//---------------------------------------------------------------Problem 4
int y = 2;
void f(int x) {y = y + 1;}
void main()
{ f(y); //CBR : y=3 //CBVR: y=2
}//---------------------------------------------------------------Problem 5 ========== Solution 1 ==========
int y = 2;
void f() {cout << y;}
void main()
{
int y = 3;
f(); }========== //lexical scope: display 2 //dynamic scope: display 3
Solution 2
==========
int z;
void f(int x)
{ int y = 10; z = x + y;
} void main(){
int y = 2;
f(y);
cout << z; //lexical scope: display 12
//dynamic scope: display 20 }
Lexical scope subsituation: int z; void main(){
int y = 2;
{ int y2 = 10; //rename of local variable z = y + y2; //subsituate x by y
} cout << z; }
Dynamic scope subsituation: int z; void main(){
int y = 2;
{ int y = 10; //NO rename of local variable z = y + y; //subsituate x by y
} cout << z;
}================ Common mistake 1 ================
int y = 2;
void f(int x) {cout << x;}
void main()
{
int y = 3;
f(y); // display 3 for both lexical and dynamic scopes
}
You can think the subsituation for both scopes be: int y = 2; void main(){
int y = 3;
{cout << y;} //so y is the local variable in main
}================ Common mistake 2 ================
void f() {int y = 3;} /