Summary: The C language passes copies of function arguments.
In C, all function arguments (except arrays) are passed “by value” rather than “by reference.” That is, a function receives a local copy of each argument, not the argument itself. These copies are local variables within the function. They are created and initialized automatically when the function begins, and they disappear when it ends. Like all local variables, their values can be changed without affecting variables elsewhere in the program.
We can clarify this point by adding a few statements to the SHOWME.C program. The new program, SHOWMORE.C, will change the values of the local variables in the showme function without changing the values of the original variables.
/* SHOWMORE.C: Demonstrate passing by value. */
#include <stdio.h>
void showme( int any, int old, int name );
main()
{
int x = 10, y = 20, z = 30;
showme( z, y, x );
printf( " z=%d y=%d x=%d\n", z, y, x );
}
void showme( int any, int old, int name )
{
printf( "any=%d old=%d name=%d\n", any, old, name );
any = 55;
old = 66;
name = 77;
printf( "any=%d old=%d name=%d\n", any, old, name );
}
Here is the output from SHOWMORE.C:
any=30 old=20 name=10
any=55 old=66 name=77
z=30 y=20 x=10
First, note that the showme function in SHOWMORE.C uses new names ( any, old, and name) when assigning the parameters it receives:
void showme( int any, int old, int name )
Summary: Function parameters can have any legal variable names.
Because these variables are local to the function, they can have any legal names. (For more information on the rules for variable names, see “Specifying Variables”.) The showme function prints the values of its parameters immediately after assigning them:
printf( "any=%d old=%d name=%d", any, old, name );
Then the function assigns new values to the variables and prints them again:
any = 55;
old = 66;
name = 77;
printf( "any=%d old=%d name=%d", any, old, name );
Summary: Local variables are private to the function containing them.
Changing the local variables in the showme function doesn't affect the
original variables in the main function. Remember, a variable defined inside
a function is only visible inside that function. After control returns to main, SHOWMORE.C prints the values of the original variables:
printf( " z=%d y=%d x=%d\n", z, y, x );
As the program output shows, the original values are unchanged:
z=30 y=20 x=10
We'll say more about the visibility of variables in Chapter 5, “Advanced Data Types.” For now, just remember that when you pass a value to a function, the function makes a local copy of that value. The local copy can be manipulated without changing the original.
NOTE:
In QuickPascal, you can pass either the value of an argument or the argument's address. In C, function arguments are only passed by value. However, that value can be an address. Chapter 8, “Pointers,” explains how to pass addresses to functions.