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.

/* a macro swap(t,x,y) that interchanges two arguments of type t */

#include<stdio.h>

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

int main(void) {
    char x, y;
    x = 'a';
    y = 'b';
    printf("x= %c \t y= %c\n", x, y);
    swap(char, x, y);
    printf("x=%c \t y=%c\n", x, y);
}

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