可以将代码块用作C宏的参数吗? [英] Is it OK to use a code block as an argument for a C macro?
问题描述
我的模式基本上是一些样板代码,中间部分有所不同
I have a pattern that is basically some boilerplate code with a part that varies in the middle
if(condition){
struct Foo m = start_stuff();
{ m.foo = bar(1,2); m.baz = 17; } //this part varies
end_stuff();
}
可以使中间代码块作为参数的宏指令吗? C语言中的宏扩展规则似乎非常复杂,因此我不确定将来是否会遇到任何麻烦的情况(特别是我不理解如果我的代码如何分隔宏参数)里面有逗号).
Is it OK to make a macro taht takes that intermediate code block as an argument? The rules for macro expansion in C seem awfully complicated so I am not sure if there aren't any corner cases that could come and bite me in the future (in particular, I don't understand how the macro arguments are separated if my code has commas in it).
#define MY_MACRO(typ, do_stuff) do { \
if(condition){ \
struct typ m = start_stuff(); \
do_stuff; \
end_stuff(); \
} \
}while(0)
//usage
MY_MACRO(Foo, {
m.foo = bar(1,2);
m.baz = 17;
});
到目前为止,我唯一想到的是,如果我在宏中使用循环语句,则会捕获break
和continue
,这对于我的特定用例来说是可以接受的折衷.
So far the only thing that I managed to think of is break
and continue
getting captured if I use looping statements in my macro and that would be an acceptable tradeoff for my particular use case.
当然,如果可以的话,我会使用一个函数.我在此问题中使用的示例经过了简化,没有展示仅适用于宏魔术的部分.
edit: Of course, I would have used a functions if I could. The example I used in this question is simplified and doesn't showcase the bits that can only work with macro magic.
推荐答案
您可以将代码块放入宏参数中,前提是它没有不加保护的逗号.在您的示例中,参数中唯一的逗号受到保护,因为它用括号括起来.
You can put a code block into a macro argument provided that it has no unguarded comma. In your example, the only comma in the argument is guarded because it is surrounded by parentheses.
请注意,仅 括号用逗号括起来.括号([]
)和花括号({}
)不在.
Note that only parentheses guard commas. Brackets ([]
) and braces ({}
) do not.
这篇关于可以将代码块用作C宏的参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!