C/C++ Arena

Step 2 of 10

Change the caller's variable

Remember from the functions module: C passes arguments by value. A function gets copies, so it can't change the caller's variables. Pointers are the way around that. If you pass a variable's address, the function gets a copy of the address, and a copy of an address still points at the original variable.

#include <stdio.h>

void add_points(int *score, int points) {
    *score += points;
}

int main(void) {
    int score = 10;
    add_points(&score, 5);
    add_points(&score, 20);
    printf("%d\n", score);
    return 0;
}
35

Follow the data:

  1. main calls add_points(&score, 5). The parameter score inside the function receives the address of main's score.
  2. *score += points follows that address and changes main's variable.
  3. When the function returns, its own variables disappear, but the change it made through the pointer stays.

This is exactly how scanf("%d", &x) works: you give it the address, and it writes the number there.

Swapping

A swap function is the classic example: it must change two of the caller's variables, which return can't do. The body is the same three-step swap you used with arrays (save one value in a temporary, copy the other over it, put the saved value in the second), just done through *a and *b.

Calling it requires addresses: swap(&x, &y). Passing x and y without & is rejected here (incompatible integer to pointer conversion), because an int isn't an int *. Some older compilers only warn about it, but the program would then treat the numbers as addresses, so always treat that message as an error.

Your turn: write void swap(int *a, int *b) that exchanges the two values.

Previous: Addresses and pointers Next: Returning two results