print_once, how blockwise it is working?

丶灬走出姿态 提交于 2019-12-02 01:52:32

That's not standard C, it uses a GCC extension called statement expressions (the funny ({...}) syntax). (It's not thread-safe either.)

It works by adding a static boolean at each print_once call site (each call site gets its own static flag), initially false, which is set to true the first time that piece of code is run (the code only prints if it was indeed false). So subsequent executions of the same block of code won't print anything.

Note that the use of the GCC extension is not necessary, and the construction of the macro is strange - it was probably extended from something simpler. This should be C99-compatible (C99 or above required for the variadic macro), and has the do {...} while(0) "trick" in the right place:

#define print_once(fmt, ...) \
do { static bool flag = false;  \
     if (!flag) { \
       flag = true; \
       printf(fmt, ##__VA_ARGS__); \
     } \
} while (0)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!