论坛首页 编程语言技术论坛

Tricks of C macros

浏览 2028 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2010-11-17   最后修改:2010-11-17
C

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