basics · beginner · ~15 min

Swap via pointers

Why pointers exist: a function can mutate caller-owned values.

Challenge

Exchange the values of two integers through pointers — your first pass-by-pointer function.

Task

Implement void swap(int *a, int *b) that swaps the integers *a and *b. No main — the grader calls it.

Input

Two non-NULL pointers a and b, each pointing to an int.

Output

Nothing is returned. After the call, *a holds the old *b and vice versa.

Example

int x=3, y=5; swap(&x, &y);   ->   x=5, y=3

Edge cases

  • Equal values: nothing visibly changes.
  • swap(&g, &g) (same address twice): the value must stay unchanged.

Rules

  • Use a temporary local variable to hold one value during the exchange.

Input format

Two non-NULL int pointers a and b.

Output format

Nothing returned; *a and *b are exchanged.

Constraints

Use a temporary; self-swap (same address) must leave the value unchanged.

Starter code

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

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