In C, all function arguments are passed "by value.". This means that the called function is given the values of its arguments in temporary variables rather than the originals.
Call by value is an asset, however, not a liability. It usually leads to more compact programs with fewer extraneous variables, because parameters can be treated as coveniently initialized local variables in the called routine.
For example,
- /* power: raise base to n-th power; n >= 0 */
-
int power (int base, int n)
-
{
-
int p;
-
-
for (p = 1; n > 0 ; --n)
-
p = p * base;
-
return p;
-
}
The parameter n is used as a temporary variable, adn is counted down (a for loop that runs backwards) until it becomes zero; there is no longer a need for the variable i. Whatever is done to n inside power has no effect on the argument that power was originally called with.
The story is different for arrays. When the name of an array is used as an argument, the value passed to the function is the location or address of the beginning of the array --- there is no copying of array elements. By subscripting this vaule, the function can access and alter any argument of the array.
阅读(1256) | 评论(0) | 转发(0) |