Lesson 3 of 8 · Functions and Arrays · 3 min read · Updated

Pass by value and pass by reference

Why a function gets a copy of your variable, and how passing its address lets it change the original.

By value, the function changes a copy and the original stays 5. By reference, it follows the address and changes the real x to 99.
c
#include <stdio.h>

void by_value(int n)
{
    n = 99;            /* changes only the copy */
}

void by_reference(int *p)
{
    *p = 99;           /* changes what p points at */
}

int main(void)
{
    int x = 5;

    by_value(x);
    printf("after by_value:     x = %d\n", x);

    by_reference(&x);
    printf("after by_reference: x = %d\n", x);
    return 0;
}
Output
after by_value:     x = 5
after by_reference: x = 99
  • Pass by value: by_value(x) sends a copy of 5. The function's n is a separate box; changing it cannot touch x.
  • Pass by reference: by_reference(&x) sends x's address. *p = 99 writes into that address — into x itself.

Getting two answers back

c
#include <stdio.h>

void min_max(int a[], int n, int *min, int *max)
{
    *min = *max = a[0];
    for (int i = 1; i < n; i++) {
        if (a[i] < *min) *min = a[i];
        if (a[i] > *max) *max = a[i];
    }
}

int main(void)
{
    int marks[] = {72, 45, 91, 60, 88};
    int lo, hi;

    min_max(marks, 5, &lo, &hi);
    printf("lowest %d, highest %d\n", lo, hi);
    return 0;
}
Output
lowest 45, highest 91

return can hand back only one value. Passing addresses lets a function fill in as many results as you need. Notice that the array itself was not copied: an array is always passed as the address of its first element, so a function can change an array's contents directly.

Note

Strictly speaking, C only has pass by value — what "by reference" really does is pass the value of an address. The effect is the same, and the Pointers topic explains exactly how it works.

To let void reset(...) set a caller's int count to 0, how should it be called?

Try this now

  1. Write void swap(int *a, int *b) and use it to swap two numbers the user types.
  2. Write void divide(int a, int b, int *quotient, int *remainder) and print both results for 17 and 5.
  3. Write void double_all(int a[], int n) that doubles every element, and print the array before and after.

Create a free account to save your progress, or sign in.