Macro that interchanges 2 arguments Define a macro swap(t, x, y) that interchanges two arguments of type t.(Block structure will help.)


The ideea is that a variable defined in a block structure exists only inside the block structure. So, I can create a temporary variable without affecting the code.

Here is my solution:

#include &lt;stdio.h&gt;

#define swap(t, x, y) {t tmp = x; x = y; y = tmp;}

int main() {
    int x = 10, y = 2;
    swap(int, x, y);

    printf("%d %d", x, y);
    return 0;
}
If you are using GCC, we can use the typeof()(C99) keyword to get rid of one of the arguments.  Also, add a do-while so the macro to be used in contexts where it would otherwise be problematic.

#define SWAP(a, b) do { typeof(a) t; t = a; a = b; b = t; } while(0)




You could also use an exclusive-or (^=) to get rid of that temporary variable, but that only works for integers.

#define SWAP(a, b) do { a ^= b; b ^= a; a ^= b; } while(0)