程式語言 - GNU - 交換變數(無需暫存變數)



main.c

#include <stdio.h>

int main(int argc, char **argv)
{
    int a, b;

    a = 1;
    b = -2;

    printf("before: a=%d, b=%d\n", a, b);
    a = a ^ b;
    b = a ^ b;
    a = a ^ b;
    printf("after: a=%d, b=%d\n", a, b);

    return 0;
}

結果

before: a=1, b=-2
after: a=-2, b=1