Pass by Reference in C

Level 4123 keystrokes

The swap function receives the addresses of x and y and exchanges the values they point to, so the caller's variables change and "10 5" is printed.

C code

// Takes pointers so it can change the caller's variables, not copies
1void swap(int *a, int *b) {
// Saves the value a points to (5) in temp
2 int temp = *a;
// Copies the value b points to (10) into the place a points to
3 *a = *b;
// Writes the saved value 5 to the place b points to
4 *b = temp;
5}
6
// The two variables whose values will be swapped
7int x = 5, y = 10;
// Passes the addresses of x and y with the & operator
8swap(&x, &y);
// x is now 10 and y is 5, so this prints 10 5
9printf("%d %d\n", x, y);

Output

10 5
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C code and how often they appear.

  • ;× 6
  • *× 6
  • ,× 5
  • =× 5
  • (× 3
  • )× 3
  • "× 2
  • &× 2
  • %× 2
  • {× 1

More C examples at level 4

← C typing practice