LOGBOOK

HELP

Quiz Entry - updated: 2026.07.10

How do you swap two variables using pointers in C?

Pass the variables' addresses (swap(&x, &y)) so the function can dereference the pointers and write back to the originals — passing the values themselves can't work, since C copies them.

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

int main() {
    int x = 5, y = 10;
    // Pass addresses!
    swap(&x, &y);
    // Now x = 10, y = 5
}

Why this works:

  • swap receives copies of the addresses (pointers)
  • But those addresses point to the original variables
  • Writing through the pointers modifies the originals

Why this DOESN'T work:

// Pass by value
void broken_swap(int a, int b) {
    int temp = a;
    a = b;
    b = temp;
// Changes are lost when function returns!
}

XOR swap (no temp variable):

void xor_swap(int *a, int *b) {
    // Must check - XOR swap fails if same address!
    if (a != b) {
        *a ^= *b;
        *b ^= *a;
        *a ^= *b;
    }
}

From Quiz: REVE1 / C Programming | Updated: Jul 10, 2026