Sams Teach Yourself C in 21 Days

(singke) #1

  1. The argument expression is evaluated.

  2. The result is copied onto the stack,a temporary storage area in memory.

  3. The function retrieves the argument’s value from the stack.
    The main point is that if a variable is passed as the argument, code in the function cannot
    modify the value of the variable. Figure 18.1 illustrates passing an argument by value. In
    this case, the argument is a simple type intvariable, but the principle is the same for
    other variable types and more complex expressions.


516 Day 18

FIGURE18.1
Passing an argument
by value. The function
can’t modify the origi-
nal argument variable.

(^1000100116)
1002
(^1003).
..
..
..
..
..
..
..
.
16
Memory
Stack
Function can access
the value of x
Value of x copied
onto the stack
int half (int y)
{
return y/2;
}
w = half (x);x
When a variable is passed to a function by value, the function has access to the variable’s
value but not to the original copy of the variable. As a result, the code in the function
can’t modify the original variable. This is the main reason why passing by value is the
default method of passing arguments: Data outside a function is protected from inadver-
tent modification.
There is another way to pass an argument to a function. Passing arguments by value is
possible with the basic data types (char,short,int,long,long long,float,double,
andlong double) and structures. The alternative method is to pass a pointer to the argu-
ment variable rather than the value of the variable itself. This method of passing an argu-
ment is called passing by reference. Because the function has the address of the actual
variable, the function can modify the variable’s value.
As you learned on Day 9, “Understanding Pointers,” passing by reference is the only way
to pass an array to a function; passing an array by value is not possible. With other data
types, however, you can use either method. If your program uses large structures, passing
them by value might cause your program to run out of stack space. Aside from this
29 448201x-CH18 8/13/02 11:14 AM Page 516

Free download pdf