Exercise 4.14 - swap that interchanges two arguments of type t

Question

Define a macro swap(t,x,y) that interchanges two arguments of type t.

/**
 * Exercise 4.14 of The C Programming Language by Brian Kernighan and Dennis
 * Ritchie
 *
 * Write a macro swap(t,x,y) that interchanges two arguments of type t. (Block
 * structure will help.)
 *
 */

#include <stdio.h>

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

int main() {
    int x = 1;
    int y = 2;
    printf("x = %d, y = %d\n", x, y);
    swap(int, x, y);
    printf("x = %d, y = %d\n", x, y);
    return 0;
}

Explanation

There are two types of macros in C namely object-like and function-like. In object type, we do substitution and in function macros we can send a variable as argument. In this program we are going to use function-like macro to swap.

We do this by defining macro:

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

In the macro, we send type t as an argument and two variables x and y to swap. We create a temperorary variable called _z of type t and use it to swap x and y.

Visualize It

Try It