Prev 09 | Control structures | Chapter 8 not section 5 | lab09 C/C++ Control |
10 | Subprograms | Chapter 9 not sect'ns 10..12 | lab10 C/C++ Functions |
Next | ** Project Phase 1 Resubmit | Old UML and proposed changes (10 pts) | |
11 | LISP | Chapter 2 section 4 + LISP handout | lab11 LISP101 |
Answer review questions on this chapter.
Hand in answers to 3 or more review questions;
template <typename T> T max( T x, T y ) { return x>=y ? x : y ; }
Call by name is a common result of using a macro. The compiler makes a copy of the subprogram body and writes in the actual parameters in place of the formal parameters. The resulting code is then executed in place of the call. For example, in C++ define:
#define zark(x) x=3*(x)+1;and then if you write the call
zark(example)the compiler creates the code
example=3*(example)+1;and that is compiled an run instead. And if you write the following call
zark( i++)then you get this effect
i++ = 3*(i++) +1;In Algol 60 compilers pass by name was handled by creating a special temporary subprogram for each such parameter. It was called a "thunk"! Each reference to the formal parameter was compiled as a call to the thunk. The thunk could evaluate the actual expression or return a left-hand value.
In K&R C all function arguments were passed by value. This is an in mode. However an address (a reference to an object ) is a valid value (shown like this: &variable_name) and so could be passed to a function. A function that was passed an address of an object of type T had an argument declared like this T*argument_name. In the body of the function this could be de-referenced (by using this syntax *argument_name ) to get to a T. So by explicit referencing (&) and de-referencing(*) we get pass by reference (an in-out mode). For example:
void add1to(int *i) { (*i)++;}
....
int i=0, j=0;
add1to(&i);
add1to(&j);This mechanism proved to be unsafe when normal programmers used them. If a program missed out the '&' in a call then the program would compile and run. The program would then mysteriously work, fail, or crash until the missing & was diagnosed. Similarly a missing or extra '*' in a function body would cause mysterious bugs and crashes. In C++ we have call by value(in), call by reference(in-out), call by constant reference(in). The old C tricky &* is still there but hidden! The C++ is more reliable than human hand coded pass by reference.