RUN

Pointers: swap two numbers in C

Pass addresses to a function so it can change the caller’s variables. Press Run to try it, then change the code and run it again.

main.c

#include <stdio.h>

void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

int main(void) {
    int x = 5, y = 10;
    printf("Before: x = %d, y = %d\n", x, y);
    swap(&x, &y);
    printf("After:  x = %d, y = %d\n", x, y);
    printf("x lives at address %p\n", (void *)&x);
    return 0;
}
Output

Press Run to see the output.

More C examples

Open the full C online compiler →