一些 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()。

1 Comments:
這個 macro 在遇到
debug_printf("no params");
這樣的用法時,會展開成
printf("no params",);
(注意逗號),然後就出問題了。
GNU cpp 和 C99 都有對應解法,gnu cpp info 的 Variadic Macros 這一節有說明。
By
Anonymous, at 3:13 PM
Post a Comment
Links to this post:
Create a Link
<< Home