basics · beginner · ~15 min

Swap two integers

Mutate caller variables via pointers.

Challenge

Exchange the values of two variables through pointers.

Task

Implement void swap_int(int *a, int *b) that swaps the integers pointed to by a and b, so that after the call *a holds the old *b and vice versa. No main — the grader calls it.

Input

Two non-NULL pointers a and b to ints.

Output

No return value. After the call, the two pointed-to values are exchanged.

Example

x = 3, y = 7;  swap_int(&x, &y)   ->   x == 7, y == 3
p = 1, q = 1;  swap_int(&p, &q)   ->   p == 1, q == 1

Edge cases

  • Swapping two equal values leaves them unchanged.

Rules

  • Use a temporary so you don't clobber a value before reading it.

Input format

Two non-NULL int pointers a and b.

Output format

No return value; the two pointed-to values are exchanged.

Starter code

void swap_int(int *a, int *b) {
    /* TODO */
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.