영어로 읽는 코딩

09 [C] call by value, pointer, call by reference

int power(int base, int n)
{
    int p;

	p = 1;
	for (p = 1; n > 0; --n)
		p = p * base;
	return p;
}

 

* Call by value, Pointer, Call by reference

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. This leads to some different properties than are seen with “call by reference" languages like Fortran or with var parameters in Pascal, in which the called routine has access to the original argument, not a local copy.

The main distinction is that in C the called function cannot directly alter a variable in the calling function; it can only alter its private, temporary copy. 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 conveniently initialized local variables in the called routine. 

The parameter n is used as a temporary variable, and 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.

When necessary, it is possible to arrange for a function to modify a variable in a calling routine. The caller must provide the address of the variable to be set (technically a pointer to the variable), and the called function must declare the parameter to be a pointer and access the variable indirectly through it. 

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 value, the function can access and alter any element of the array

 

[The C Programming Language (second edition, Prentice Hall) by Brian W. Kernighan and Dennis M. RitchieS]

댓글

댓글 본문
버전 관리
Yoo Moon Il
현재 버전
선택 버전
graphittie 자세히 보기