Tricks of C macros

Sample code showing some tricks of C macro usage.

 

 

 

#include <stdio.h>

/*
 * Argument concatenation
 */
#define concatenate(front, back) front ## back

/* 
 * GNU C extension. Refer to 
 * http://gcc.gnu.org/onlinedocs/gcc-2.95.3/gcc_4.html#SEC76 
 */
#define gnu_eprintf(format, args...) \
    fprintf(stderr, format, ##args)

/*
 * C99
 */
#define c99_eprintf(format, ...) \
    fprintf(stderr, format, __VA_ARGS__)

/*
 * do-while used to enclose multiple statements
 */
#define print_two_times(str) do { \
    printf("1: %s\n", str); \
    printf("2: %s\n", str); \
} while(/*CONSTCOND*/0)

/*
 * show the effect of missing arguments
 */
#define NODE(name, type, qual)  \
struct name { \
    qual type value; \
    qual struct name *next; \
}

int main(int argc, const char *argv[]) 
{
    printf("concatenation: %d\n", sizeof(concatenate(fl, oat)));
    gnu_eprintf("%d %d %d\n", 1, 2, 3);
    c99_eprintf("%d %d %d\n", 1, 2, 3);
    print_two_times("a little message");

    NODE(tree_node, int, ) one;
    one.value = 1000;
    printf("node value: %d\n", one.value);
    return 0;
}

你可能感兴趣的:(html,C++,c,C#,gcc)