将块指令作为C中的宏参数传递 [英] pass block instruction as macro's argument in C
问题描述
我不知道这是否可行,我想像参数一样在宏中传递指令块.我将向您展示一个示例:
I don't know if that is possible, I want to pass a block of instructions in macro like an argument.I will show you an example:
#define ADD_MACRO(size, BLOCK){ for(int i=0; i<size; i++){\
BLOCK} }
您怎么看?
感谢帮助
推荐答案
给定宏的唯一问题是它不处理BLOCK
中的逗号.可变参数宏参数允许使用逗号:
The only problem with the given macro is that it doesn't handle commas in the BLOCK
. Commas are tolerated by a variadic macro parameter:
#define ADD_MACRO(size, ...) do { for(int i=0; i<size; i++){\
__VA_ARGS__} } while(0)
(此外,通常的做法是将语句宏包含在do … while(0)
中,以强制用户包括分号.)
(Also, common practice is to enclose statement macros in do … while(0)
to force the user to include a semicolon.)
(当然,最初的问题可能有更好的解决方案.预处理器是一种钝器.这是针对所述问题的预处理器解决方案.)
(Of course, the original problem may have a better solution. The preprocessor is a blunt instrument. This is the preprocessor solution to the stated question.)
这篇关于将块指令作为C中的宏参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!