Pass by value and pass by reference

With the exception of arrays and functions , C always passes arguments `by value': a copy of the value of each argument is passed to the function; the function cannot modify the actual argument passed to it:


void foo(int j) {
j = 0; /* modifies the copy of
the argument received by the function */
}

int main(void) {
int k=10;
foo(k);
/* k still equals 10 */
}
If you do want a function to modify its argument you can obtain the desired effect using pointer arguments instead:


void foo(int *j) {
*j = 0;
}

int main(void) {
int k=10;
foo(&k);
/* k now equals 0 */
}
This is sometimes known as `pass by reference' in other languages.

Comments

Popular posts from this blog

BIP Formatting

Repeat Table Header in all pages in BIP

Limit rows per page