Functions on Call

When we use functions in C, a very specific sequence of events takes place:
  1. Each of the arguments are evaluated. That is, we perform any calculations that are necessary to get a single value for that argument.
  2. The function is called with the arguments passed to it. Calling a function temporarily transfers the control of the program to that function. By passing of arguments we mean that the values which were determined for the arguments in Step 1, are made available to function being called.
  3. The function executes the statements in it's body.
  4. The called function then returns to the calling function. (We will often refer to the called function as the callee and the calling function as the caller.) The callee may compute a return value which is then sent back to the caller.

By way of example, let us look at the call to the function sqrt():

sqrt( square( side_a ) + square( side_b ))

that we saw in Part 2-1. Here the function sqrt() (which computes square roots) has one argument, the expression:

square( side_a ) + square( side_b )

When we call sqrt(), we first evaluate this expression. In order to evaluate it, we must make two function calls and add the results. For the first of these calls, we pass the value of the variable side_a to the function square(). Suppose that the value of side_a is 4.0. Then after we've called square() on side_a but before calling it on side_b it's as if the expression were

16.0 + square( side_b )

Then we call square on side_b. If side_b is 3.0, then we now have the expression:

16.0 + 9.0

which evaluates to 25.0 which is the value passed to sqrt(). It then returns with the value 5.0. So our return statement is as if we had typed:

return( 25.0 ) ;

and 25.0 becomes the value of the call:

pythag( adjacent, opposite )

where adjacent is 4.0 and opposite is 3.0.

Consider the following code:
a = 5 ;
b = foo( a, 3 ) ;
printf( "%d, %d, %d", a, b, foo( a, b )) ;
int foo( int x, int y )
   int z ;

   z = x * y ;
   return( z ) ;
What will the printed numbers be?

5, 15, 15
5, 8, 40
5, 8, 13
5, 5, 5
5, 15, 75