Back to Blog

C in 100 Seconds: Pass by Reference | Episode 19

Daryl WongDaryl Wong

Video: C in 100 Seconds: Pass by Reference — Pointers as Parameters | Episode 19 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Pass by Reference — Modifying Variables Through Pointers

C in 100 Seconds, Episode 19


By default, C functions receive copies of their arguments. Change the copy inside the function and the original is untouched. To actually modify the caller's variables, you pass pointers.

The Problem: Pass by Value

void no_swap(int a, int b) {
  int temp = a;
  a = b;
  b = temp;
}

This function swaps its local copies of a and b. The caller's variables don't change:

int x = 10, y = 20;
no_swap(x, y);
// x is still 10, y is still 20

The values were copied into the function. The originals are completely isolated.

The Solution: Pass by Reference

Pass pointers instead of values:

void swap(int *a, int *b) {
  int temp = *a;
  *a = *b;
  *b = temp;
}

Now the function receives addresses. Dereferencing those addresses (*a, *b) modifies the original variables:

swap(&x, &y);
// x is now 20, y is now 10

The & operator passes the address. The * operator inside the function follows it back to the original data.

Why Does This Matter?

Pass by reference is how C functions communicate changes back to the caller. Without it:

  • You couldn't write a function that modifies multiple values
  • scanf couldn't fill your variables (that's why it needs &)
  • Returning large data would require expensive copies

This pattern — taking pointer parameters and dereferencing them — is one of the most common patterns in C code.

Full Code

#include <stdio.h>

void no_swap(int a, int b) {
  int temp = a;
  a = b;
  b = temp;
}

void swap(int *a, int *b) {
  int temp = *a;
  *a = *b;
  *b = temp;
}

int main() {
  int x = 10, y = 20;

  printf("Before no_swap: x=%d y=%d\n", x, y);
  no_swap(x, y);
  printf("After no_swap:  x=%d y=%d\n", x, y);

  printf("\nBefore swap: x=%d y=%d\n", x, y);
  swap(&x, &y);
  printf("After swap:  x=%d y=%d\n", x, y);

  return 0;
}

Compile and Run

gcc passbyref.c -o passbyref
./passbyref

Next episode: malloc and free — allocating memory on the heap.

Student code: github.com/GoCelesteAI/c-in-100-seconds/episode19