C functions and pointer parameters

Modify caller-owned values through valid addresses.

C
#include <stdio.h>
#include <assert.h>
void swap(int *a, int *b) {
    int temporary = *a;
    *a = *b;
    *b = temporary;
}
int main(void) {
    int x = 3, y = 8;
    swap(&x, &y);
    printf("%d %d\n", x, y);
    swap(&x, &x);
    assert(x == 8 && y == 3);
    return 0;
}
Output
8 3

Explanation

C passes arguments by value, including pointer arguments. Copying an address into a parameter still lets the function access the original object at that address.

swap saves one value before overwriting either object. Both pointers must point to live, writable int objects.

Explore the dry run
Guided walkthroughReady
1#include <stdio.h>
2#include <assert.h>
3void swap(int *a, int *b) {
4 int temporary = *a;
5 *a = *b;
6 *b = temporary;
7}
8int main(void) {
9 int x = 3, y = 8;
10 swap(&x, &y);
11 printf("%d %d\n", x, y);
12 swap(&x, &x);
13 assert(x == 8 && y == 3);
14 return 0;
15}

Follow the example

Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.

View the complete dry-run table
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput so far
Create the caller's variables.x = 3, y = 8
—
Pass copies of their addresses.a = &x, b = &y
—
Save x before overwriting it.temporary = 3
—
Write y into x.x = 8, y = 8
—
Write the saved value into y.x = 8, y = 3
—
Print the swapped values.x = 8, y = 3
8 3
Swapping an object with itself leaves it unchanged.x = 8, y = 3
8 3

Cost and common mistakes

O(1) time and auxiliary space.

  • Dereferencing NULL or a dangling pointer is invalid.
  • Swapping plain int parameters would only change local copies.

Try it yourself

Trace swapping x=5 and y=5.

Reveal answer and reasoning

The temporary is 5, both assignments store 5, and the two values remain equal.

Further reading