Praveen's Blog

An Eternal Quest for Incremental Improvement

Swapping integers without using a temporary variable

This might be of interest for those sitting for placement. How do you swap two integers in C without creating a temporary variable ?

#include <stdio .h>
int main(void)
{
        int a = 100;
        int b = 200;

        printf("a=%d | b=%d\n",a,b);
        a ^= b ^= a ^= b;
        printf("a=%d | b=%d\n",a,b);
        return 0;
}

Found it on the usenet C FAQ, question 3.3b. It comes with a warning that the code might not be portable across compilers.

Courtesy: Anand Kumar Saha


Comments