LOGBOOK

HELP

Quiz Entry - updated: 2026.07.10

What is the difference between pass by value and pass by reference in C?

C always passes by value (a copy), so to let a callee modify a caller's variable you pass that variable's address and the callee writes through the pointer.

Pass by value vs by reference

* By value the callee edits a private copy (the caller is unchanged); to modify the caller's variable you pass its address and write through the pointer. *

Pass by value (copy):

void cant_modify(int x) {
    // Only modifies local copy!
    x = 100;
}

int a = 5;
cant_modify(a);
// a is still 5

Simulate pass by reference with pointers:

void can_modify(int *x) {
    // Modifies through pointer
    *x = 100;
}

int a = 5;
// Pass address of a
can_modify(&a);
// a is now 100

Why pass by reference?

  1. Modify caller's variables (like swap)
  2. Efficiency - avoid copying large structs
  3. Return multiple values (through parameters)
// Swap example:
void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

int x = 5, y = 10;
// x=10, y=5
swap(&x, &y);

Arrays are always "by reference":

// Receives pointer, not copy
void modify_array(int arr[]) {
    // Modifies original!
    arr[0] = 100;
}

Go deeper:

From Quiz: REVE1 / C Programming | Updated: Jul 10, 2026