函数式宏与宏 [英] function-like macro versus macros
问题描述
gcc (GCC) 4.7.2
c89
你好
我一直在看一个测试套件,我注意到这样声明的类似于函数的宏是这样的:
I have been looking at a test suite and I noticed this function-like macro declared like this:
#define MU_SUITE_START() char *msg = NULL
但是,执行此操作有什么真正的区别:
However, is there any real difference to doing just this instead:
#define MU_SUITE_START char *msg = NULL
宏只做文本替换,所以我认为不会有任何性能问题.
Macros just do text replacement so I don't think there is going to be any performance issues.
使用cpp我得到以下结果,所以这里没什么特别的.
Using cpp I get the following results so nothing special here.
类似函数的宏
char *msg = __null;
马可
char *msg = __null;
请注意:是否值得声明输入参数中未提供的类似函数的marco? 这里我没有传递任何参数 即
Just a side note: Is it worth declaring a function-like marco that doesn't provide in input parameters? Here I am not passing any parameters i.e.
#define PRINT_MSG() printf("This is the message\n")
如果没有输入参数,为什么还要烦扰类似于函数的宏,这不是更好吗?
Why bother with the function-like macro if there are no input parameters, isn't this better?
#define PRINT_MSG printf("This is the message\n")
非常感谢您的任何建议,
Many thanks for any suggestions,
推荐答案
类对象宏和类函数宏之间有一个区别:
There's one difference between the object-like and function-like macros:
#define OBJECT char *msg1 = NULL
#define FUNCTION() char *msg2 = NULL
void somefunc(void)
{
int OBJECT = 5;
int FUNCTION = 10;
...
}
OBJECT
的声明被宏替换(因此代码不会编译),但是对FUNCTION的引用不是宏调用,因为它后面没有括号.
The declaration for OBJECT
is replaced by the macro (so the code won't compile), but the reference to FUNCTION is not a macro invocation because it is not followed by an open parenthesis.
这很少重要.但是,确实如此很重要.
This is seldom important. However, when it is, it really matters.
更典型的情况是可以实现为宏的函数.为了讨论起见(因为它很容易理解,而不是因为它是一个很好的例子):
A more typical case might be a function that can be implemented as a macro. For sake of discussion (because it is easily understood rather than because it is a good example):
extern int isdigit(int c);
#define isdigit(c) ((c) >= '0' && (c) <= '9')
并在实现文件中:
int (isdigit)(int c)
{
assert((c >= 0 && c <= UCHAR_MAX) || c == EOF);
return isdigit(c);
}
忽略这样的小细节并不是实现isdigit()
的方式,并且isdigit()
的宏实现不允许多次评估其自变量,并且您不应该重新定义那些在标准C库中,函数定义未进行宏扩展,因为名称isdigit
后没有(
,但是函数内部的宏已扩展.至少该功能是在宏方面实现的,几乎可以保证相同的行为.
Ignoring little details like that isn't how isdigit()
is likely to be implemented, and a macro implementation of isdigit()
is not allowed to evaluate its argument more than once, and you aren't supposed to redefine things that are in the standard C library, the function definition is not macro expanded because the name isdigit
is not followed by (
, but the macro inside the function is expanded. At least the function is implemented in terms of the macro, which pretty much guarantees the same behaviour.
这篇关于函数式宏与宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!