HiveBrain v1.2.0
Get Started
← Back to all entries
patterncModerate

Macro that interchanges 2 arguments

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
interchangesthatmacroarguments

Problem

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 

#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;
}

Solution

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)

Code Snippets

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

Context

StackExchange Code Review Q#40180, answer score: 12

Revisions (0)

No revisions yet.