`
yaojingguo
  • 浏览: 208167 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

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;
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics