Pass by Value vs Pass a Pointer

C copies arguments. A swap function only works when it gets pointers to the caller's variables.

C · beginner · 8 min · 15 steps · free

What you'll learn

swap_pointers.c

#include <stdio.h>

void swap_copy(int a, int b) {
    int t = a;
    a = b;
    b = t;
}

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

int main(void) {
    int x = 1, y = 2;
    swap_copy(x, y);
    printf("after swap_copy: %d %d\n", x, y);
    swap(&x, &y);
    printf("after swap: %d %d\n", x, y);
    return 0;
}

Step by step

  1. x is created on the stack with the value 1. y is created on the stack with the value 2.
  2. swap_copy gets copies: a = 1, b = 2.
  3. t is created on the stack with the value 1.
  4. a changes from 1 to 2.
  5. Only the copies were swapped.
  6. swap_copy() has finished, so its variables are gone.
  7. x and y are unchanged: 1 2.
  8. &x and &y pass the addresses of x and y.
  9. t is created on the stack with the value 1.
  10. *a = *b writes through the pointer into main's x.
  11. y changes from 2 to 1.
  12. swap() has finished, so its variables are gone.
  13. It prints after swap: 2 1.
  14. The method returns 0.
  15. swap_copy did nothing visible; swap really swapped: 2 1.

Common mistakes

Best practices

Key takeaways

Check yourself

void f(int *p) { *p = 5; } f(&n); n is?

Answer: 5. Written through the pointer.

What does & give?

Answer: An address. The address of a variable.

·

More in Functions and Scope