Warning
Passing by value protects a variable. If the receiving function changes a passed-by-
value variable, the calling function’s variable is left unchanged. Therefore, passing by
value is always safe because the receiving function can’t change the passing function’s
variables—it can only use them.
If the previous program’s receiving function called its parameter i2, the program would still work
the way it does now. The i2 would be local to half(), whereas the i in main() would be local
to main(). The i2 would be local to the half() function and distinct from main().
C uses the passing by value method for all non-array variables. Therefore, if you pass any variable
that is not an array to a function, only a copy of that variable’s value is passed. The variable is left
unchanged in the calling function, no matter what the called function does with the value.
Passing by Address
When you pass an array to another function, the array is passed by address. Instead of a copy of the
array being passed, the memory address of the array is passed. The receiving function then places its
receiving parameter array over the address passed. The bottom line is that the receiving function
works with the same address as the calling function. If the receiving function changes one of the
variables in the parameter list, the calling function’s argument changes as well.
The following program passes an array to a function. The function puts X throughout the array, and
then main() prints the array. Notice that main() prints all Xs because the function changed the
argument.
Click here to view code image
// Example program #2 from Chapter 31 of Absolute Beginner's Guide
// to C, 3rd Edition
// File Chapter31ex2.c
/* The program demonstrates passing an array to a function. */
#include <stdio.h>
#include <string.h>
main()
{
char name[15] = "Michael Hatton";
change(name);
printf("Back in main(), the name is now %s.\n", name);
return(0); // Ends the program
}
/******************************************************************/
/* Sometimes putting dividers like the one above is a nice break
between your different functions. */