Gea-Suan Lin's BLOG for Work

星期三, 十一月 01, 2006

一些 C Macro 的技巧 (Part I:不定變數)

幾個學校課程不太會講到的技巧,第一個是不定變數的使用:
#ifdef DEBUG
#define debug_printf(str, ...) do { printf(str, __VA_ARGS__); } while (0)
#else
#define debug_printf(str, ...)
#endif

關鍵是 __VA_ARGS__,這樣可以很愉快的使用 debug_printf()

2 Comments:

  • 這個 macro 在遇到
    debug_printf("no params");
    這樣的用法時,會展開成
    printf("no params",);
    (注意逗號),然後就出問題了。

    GNU cpp 和 C99 都有對應解法,gnu cpp info 的 Variadic Macros 這一節有說明。

    By Anonymous 匿名, at 3:13 下午  

  • 太感謝了,終於解決我長久以來無法解決的問題

    By Blogger levon.chang, at 3:42 下午  

張貼意見

Links to this post:

建立連結

<< Home