Monday, January 26, 2009

Function Arguments in C Program

Look back at the function strcopy in the previous section. We passed it two string names as arguments, then proceeded to clobber both of them by incrementation. So how come we don't lose the original strings in the function that called strcopy?
As we said before, C is a ``call by value'' language: when you make a function call like f(x), the value of x is passed, not its address. So there's no way to alter x from inside f. If x is an array (char x[10]) this isn't a problem, because x is an address anyway, and you're not trying to change it, just what it addresses. This is why strcopy works as it does. And it's convenient not to have to worry about making temporary copies of the input arguments.
But what if x is a scalar and you do want to change it? In that case, you have to pass the address of x to f, and then use it as a pointer. Thus for example, to interchange two integers, we must write

flip(x, y)
int *x, *y; {
int temp;
temp = *x;
*x = *y;
*y = temp;
}

and to call flip, we have to pass the addresses of the variables:
flip (&a, &b);

No comments:

Post a Comment