Skip to content
CurriculumChapter 18 ยท Functions & Storage
IntermediateHigh focus~12 min

Call by Value vs Call by Reference

C always passes by value. To let a function modify the caller's variable, pass its address. That is how C simulates call by reference.

In plain English

C hands a function a copy, not the original. To let it change the original, you give it the address.

01

Call by value

When you pass an argument, the function receives a copy. Changing the parameter inside the function does not change the caller's variable. This is true for ints, floats, structs, and even pointers: the pointer is copied, but it still points to the same object. Arrays are different because the array name decays to a pointer.

chapter-18.cC
void bump(int n) {
    n = n + 1;      /* changes the copy only */
}

int x = 5;
bump(x);
printf("%d\n", x);  /* 5 */
02

Call by reference with pointers

To modify a caller's variable, pass its address and dereference the pointer inside the function. This is called call by reference in C, even though the language itself only passes values. The same technique lets a function return more than one result through output parameters.

chapter-18.cC
void bump(int *p) {
    (*p)++;
}

int x = 5;
bump(&x);
printf("%d\n", x);  /* 6 */

Key takeaways

  • C passes arguments by value.
  • A function receives a copy of each argument.
  • Pass a pointer to modify the caller's variable.
  • Arrays decay to pointers when passed.

Common pitfalls

  • Expecting a function to modify a value passed by value.
  • Dereferencing a NULL pointer inside a function.
  • Confusing a copied pointer with a copied pointee.

Key focus

  • Predict the output of functions that modify parameters.
  • Know the difference between call by value and call by reference.

Quick check

0 / 2 answered

1. What does C pass to a function by default?

2. How do you make a function modify an int variable from the caller?