We will tackle the following questions in groups.
b. What type is it?
c. What does the following C++ program output?
#include <iostream>
int main()
{ cout << ( 3>2 ? "bigger\n" : "smaller\n" );
cout << ( 2>3 ? "bigger\n" : "smaller\n" );
cout << ( 2>2 ? "bigger\n" : "smaller\n" );
}
c. Does this type of expression use short circuited evaluation(Y/N)? Why do you think this?
d. Can you create a C/C++/Java function that can be used as a perfect replacement for the expression (B ? E1: E2) for all expressions B, E1, and E2(Y/N)? Why?(paragraph)
Here are some questions on these operations:
a. What are the binary representations of the numbers 5 and 7?
b. What is output by the following program fragment, and why?
cout << (3 & 5) << endl
cout << (3 ^ 5) << endl
cout << (3 | 5) << endl
Answers: [ ../samples/c.syntax.html#Bitwise Expressions ]
b. Name one (1) high level programming language that doesn't have them,
c. Give one (1) reason for having them.
d. In a certain language, expressions have two operations: multiplication and addition. These are symbolized by "*" and "+" respectively. Precedence: Multiplication is done before addition. Associativity: left to right. Show how to express these rules in a syntax metalanguage like BNF/EBNF/XBNF.
[ 08.html ]
a. Draw class diagram in the UML that fits the above grammar. The diagram should show the classes: Expression, Number, Variable, FunctionCall, and Function. It should also show the relationships between them and show argument as a role_name.
Click [ ole1a.gif ] to see an answer.
b. Add operations to express the semantics: All types of expression have a method or function evaluate() that returns an int value. A Function has a method apply( ....) that takes a list of int's and returns an int result.
Click [ ole1.gif ] to see an answer.
c. Describe the evaluation of an FunctionCall in terms of a apply(...) in the Function class and evaluating the arguments of the FunctionCall.
Answer
In English: Evaluating an FunctionCall requires that the sub-expressions that make up the operands are evaluated first. Then, the Function is applied to the values obtained by evaluating its arguments:
In a C++ type language:
int FunctionCall::evaluate()
{ // A functionCall has a vector of arguments which we evaluate first.
vector<int>value;
for(int i=0; i< argument . size(); i++)
{ values.push_back( argument [i] . evaluate() );
}//end for
int return_value = function.apply(value);
return return_value;
}Note: the vector of values is used just like a stack. Further it is allocated on the stack.... Many language systems evaluate an expression using a run time stack like this example.