Monday, April 8, 2013

Concepts of Programming Languages - Chapter 7


Review Questions

2. What is a ternary operator?
A ternary operator is an operator that has three operands.

3. What is a prefix operator?
A prefix operator is an operator that precedes the operands.

4. What operator usually has right associativity?
Exponentiation operator.

5. What is a nonassociative operator?
A nonassociative operator is an operator that needs to be parenthesized to show the desired order to become legal.

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

11. What is an overloaded operator?
An overloaded operator is an arithmetic operator that is often used for more than one purpose.

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

28. What is a cast?
Explicit type conversion.


Problem Set

1. When might you want the compiler to ignore type differences in an expression?
Suppose Type1 is a subrange of Integer. It may be useful for the difference between Type1 and Integer to be ignored by the compiler in an expression.

3. Do you think the elimination of overloaded operators in your favorite language would be beneficial? Why or why not?
Yes. Because eliminating overloaded operators will increase readability and prevent compiler confusion in choosing the correct meaning of the operator.

7. Describe a situation in which the add operator in a programming language would not be commutative.
An expression such as i + fun(j)

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 expressions are evaluated left to right?
b. if the operands in the expressions are evaluated right to left?

a. left to right: sum1 is 46; sum2 is 48
b. right to left: sum1 is 48; sum2 is 46

15. Explain why it is difficult to eliminate functional side effects in C.
All functions in C are subprograms and each of them return only one value.To return more that one value, we have to use parameters and if the parameters are pointers it may change the value of variables. Another problem is if the function changes the value of a global variable, it may affect the whole program.

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 values of x after the assignment statement in main, assuming
a. operands are evaluated left to right.
b. operands are evaluated right to left.

a. 7
b. 12


No comments:

Post a Comment