Pages

Saturday 13 April 2013

Chapter 7


An assignment from Mr. Tri Djoko Wahyono (again). As what the title said, it is the answer for some question (7 numbers, quite randomly in Review Qustion and 5 or 6 numbers in Problem Set) in Chapter 7 in "Concept of Programming Language" book.


Review Question
2. What is a ternary operator?
It means, the operator have three operands.

3. What is a prefix operator?
It means the operators precede their operands.

6. What associativity rules are used by APL?
Right to left for all operators.

7. What is the difference between the way operators are implemented in C++ and Ruby?
The difference is in Ruby, all the arithmetic, relational, and assignment operator, as well as array indexing, shifts, and bitwise logic operators, are implemented as methods while in C, it doesn't.

8. Define functional side effect.
It is a side effect of a function. Occurs when the function changes either one of its parameters or a global variable.

18. What is short-circuit evaluation?
A short-circuit evaluation of an expression is one in which the result is determined without evaluating all of the operands and/or operators.

24. What two languages include multiple assignments?
Perl and Ruby.

Problem Set
1. When might you want the compiler to ignore type differences in an expression?
When I want to evaluate a string as a number and vice versa.

13. Let the function fun be defined as

int fun(int *k){
  *k += 4;
  return 3 * (*k) - 1;
}

Suppose fun is used in a program as follows:

void main(){
  int i = 10, j = 10, sum1, sum2;
  sum1 = (i/2) + fun (&i);
  sum2 = fun(&j) + (j/2);
}

What are the values of sum1 and sum2
a. if the operands in the expression are evaluated left to right?
b. if the operands in the expression are evaluated right to left?

a. sum1 = (10/2) + (3 * 10 - 1) = 5 + 29 = 34
    sum2 = (3 * 14 - 1) + (14/2) = 41 + 7 = 49


b. sum1 = (14/2) + (3 * 14 - 1) = 7 + 41 = 49
    sum2 = (3 * 10 - 1) + (10/2) = 29 + 5 = 34


15. Explain why it is difficult to eliminate functional side effects in C?
In C, it only have one functions, meaning that all subprograms return only one value. To eliminate the side effects and still provide subprograms that return more than one value, the values need to be placed in a struct and the struct returned. Access to global in functions would also have to be disallowed.


18. Should an optimizing compiler for C or C++ be allowed to change the order of subexpressions in a Boolean expression? Why or why not?
Because of short-circuit evaluation, the order of subexpressions is important.

20. Consider the following C program:

int fun(int *i){
  *i += 5;
  return 4;
}

void main(){
  int x = 3;
  x = x + fun(&x);
}


What is the value of x after the assignment statement in main, assuming
a. Operands are evaluated left to right.
b. Operands are evaluated right to left.


a. x = 3 + 4 = 7

b. x = 8 + 4 = 12

No comments:

Post a Comment