The Formality of Functions

Formals and Actuals

Notice that even when an argument expression is just a single variable, it need not be named the same thing as it is named in the function being called. The name given in the callee is called the formal parameter (or sometimes just parameter) where the argument expression is known as the actual parameter or argument. For example, we called one of the variables adjacent in the main() function and used that name passing it as the first argument when we called pythag(). However, in pythag() itself, the first parameter is called side_a. side_a is the formal parameter and for this call, adjacent is the actual parameter. It couldn't be any other way; we don't know what the formal for sqrt() is!

Positional Parameters

So the question arises, how does C know which actual goes with which formal? If we run the program:

#include <stdio.h>

void foo( int a, int b ) ;

   int a, b ;

   a = 3 ;
   b = 9 ;
   foo( a, b ) ;
   foo( b, a ) ;

void foo( int a, int b )
   printf( "%d %d\n", a, b ) ;

we see that the output looks like:
3 9
9 3
illustrating that parameters are passed by position. Namely, the first actual always corresponds to the first formal and so on. This is true whether or not the names of the actuals and formals are the same. (See Part 2-5 for an explanation of the return type void.)

Passing by Value

Another important fact about parameter passing is shown in this next example.

#include <stdio.h>

void foo( int a ) ;

   int x ;

   x = 42 ;
   foo( x ) ;
   printf( "After calling foo: x = %d\n", x ) ;

void foo( int a )
   a = 101 ;
   printf( "Inside foo: a = %d\n", a ) ;

When we run this program which number (42 or 101) will be printed for x after the call to foo()? The answer depend on what kind of parameter passing C uses. All parameter passing in C is of the type known as pass by value. (There are others, but we are not concerned with them here.) What this means is that when something is to be passed, the expression is first evaluated. If the expression is just a variable, then the value of the expression is just what's stored in the variable. Then a copy of the expression's value is placed into a new "variable" which has the name of the formal parameter. In a case like this where the argument is a single variable, we now have two copies of that number (as opposed to having both names as aliases for the same memory location). That means that any changes to a parameter made inside a function get made to it's local copy of the data, not to the actual parameter.

In the program:
#include <stdio.h>

int foo( int x ) ;

   int i, j ;

   i = foo( 3 ) ;
   j = foo( i ) ;
   printf( "%d %d\n", i, j ) ;

int foo( int x )
   x = x * 2 ;
   printf( "%d ", x ) ;
   return( x + 3 ) ;
What is the output from this program?

6 18 12 21
6 18 9 21
9 21 6 18
9 21 9 21
6 12 6 12