为什么我的简单的C宏观调控工作? [英] Why doesn't my simple C macro work?
问题描述
我想打一个简单的宏调用的printf()两次这样的
I want to make a simple macro that calls printf() twice like this
#ifdef ENABLE_DEBUGPRINTF
#define DEBUGPRINTF(msg) printf("At sim_time = %f:", sim_time); printf(msg);
#else
#define DEBUGPRINTF(msg) //evalutes to nothing
#endif
现在,当我打电话
DEBUGPRINTF("Processed event type: %d with value %f\n", id, data)
它打印出的第一部分在sime_time = ...正确,但它说:处理的事件......后期打印的ID和数据不正确的值。
It prints the first part "At sime_time = ... " correctly but the latter part where it says "Processed events ... " prints the value for id and data incorrectly.
同时
printf("Processed event type: %d with value %f\n", id, data);
正确打印值。
当我试图通过准确写出了我认为宏观想要得到的,我有执行它。
When I try executing it by writing exactly out what I thought the macro would evaluate to, I have.
printf("At sim_time = %f:", sim_time); printf("Processed event type: %d with value %f\n", id, data);
这正常打印的一切!那么,为什么不是我的宏观评估这样做呢?
This prints everything correctly! So why isn't my macro evaluating to this?
推荐答案
由于你想和使用的常规的printf
,你想要的是一个宏观的充分的灵活性以可变参数
参数:
Because you want and are using the full flexibility of a regular printf
, what you want is a macro with a variadic
argument:
#ifdef ENABLE_DEBUGPRINTF
#define DEBUGPRINTF(msg...) \
printf("At sim_time = %f:", sim_time); printf(msg);
#else
#define DEBUGPRINTF(msg...) /*evalutes to nothing*/
#endif
我以前做过很多次,我建议用封装做{}而(0)
:
#ifdef ENABLE_DEBUGPRINTF
#define DEBUGPRINTF(msg...) \
do { \
printf("At sim_time = %f:", sim_time); \
printf(msg); \
} while (0)
#else
#define DEBUGPRINTF(msg...) //evalutes to nothing
#endif
这允许你做的是这样的:
This allows you to do something like:
if (showit)
DEBUGPRINTF("hit the showit point -- showit=%d\n",showit);
因此,使用宏code不必知道它实际上是两个语句[或无]
Thus, the code that uses the macro doesn't have to know that it's actually two statements [or none]
更新:
DEBUGPRINTF(MSG ...)
不符合标准,但一些旧的编译器扩展。您的省略号之前错过了一个逗号。
DEBUGPRINTF(msg...)
is not standard compliant, but some legacy compiler extension. You missed a comma before the ellipsis.
也许吧,但是,我个人还是preFER它,并用它在生产中code了10多年,一直
Perhaps, but, personally, I still prefer it, and have been using it in production code for 10+ years.
然而,这里有一些资源用于那些可能希望使用其他方法:
However, here are some resources for those that might wish to use the alternative ways:
- https://gcc.gnu.org/onlinedocs/cpp/Variadic- Macros.html
- https://en.wikipedia.org/wiki/Variadic_macro
- https://gcc.gnu.org/onlinedocs/cpp/Variadic-Macros.html
- https://en.wikipedia.org/wiki/Variadic_macro
这篇关于为什么我的简单的C宏观调控工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!