Swap with Pointers in C

Level 5199 keystrokes

Defines a swap function that receives the addresses of two ints and exchanges the values stored there. Because it works through pointers, x and y in main really change: 10, 20 before the call and 20, 10 after.

C code

// Takes two int pointers, so it can change the caller's variables
1void swap(int *a, int *b) {
// Saves the value at address a (10) in a temporary variable
2 int temp = *a;
// Copies the value at address b (20) to address a
3 *a = *b;
// Writes the saved value (10) to address b, completing the swap
4 *b = temp;
5}
6
// Program entry point
7int main() {
// Declares the two values to swap
8 int x = 10, y = 20;
// Prints Before: x=10, y=20
9 printf("Before: x=%d, y=%d\n", x, y);
// Passes the addresses of x and y with &, not their values
10 swap(&x, &y);
// The values are now exchanged: prints After: x=20, y=10
11 printf("After: x=%d, y=%d\n", x, y);
// Returns 0 to report that the program ended normally
12 return 0;
13}

Output

Before: x=10, y=20
After: x=20, y=10
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.

  • ,× 9
  • =× 9
  • ;× 8
  • *× 6
  • (× 5
  • )× 5
  • "× 4
  • %× 4
  • :× 2
  • {× 2

More C examples at level 5

← C typing practice