Example of typeof to make a "swap" macro.

This is an example C program illustrating the use of the typeof extension of Gnu C to make a "swap" macro.

#include <stdio.h>

/* Swap a and b using the "typeof" extension. */

#define SWAP(a,b) {                             \
        typeof (a) c;                           \
        c = a;                                  \
        a = b;                                  \
        b = c;                                  \
    }

/* Example: swap integers. */

static void swap_int_example ()
{
    int x = 99;
    int y = 100;
    printf ("x = %d, y = %d\n", x, y);
    SWAP (x, y);
    printf ("x = %d, y = %d\n", x, y);
}

/* Example: swap structures. */

static void swap_struct_example ()
{
    struct ex {
        char * c;
        int d;
    };
    struct ex x = {
        "monkey",
        42,
    };
    struct ex y = {
        "anteater",
        99,
    };
    printf ("%s %d %s %d\n", x.c, x.d, y.c, y.d);
    SWAP (x, y);
    printf ("%s %d %s %d\n", x.c, x.d, y.c, y.d);
}

int main ()
{
    swap_int_example ();
    swap_struct_example ();
    return 0;
}

(download)

The output of the example looks like this:

x = 99, y = 100
x = 100, y = 99
monkey 42 anteater 99
anteater 99 monkey 42

Caution: if either of the arguments to SWAP have side effects, this macro will not work.


Copyright © Ben Bullock 2009-2018. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com) or use the discussion group at Google Groups. / Privacy / Disclaimer