空函数宏 [英] Empty function macros

查看:136
本文介绍了空函数宏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我定义了一个没有实际函数的函数宏,它是否与编译器中的空字符串一样(即它在编译时不会生成任何额外的指令)?

示例:

  #define SomeMacro(a)

SomeMacro(hello); //此行不添加任何说明,是吗?


解决方案

你绝对正确, t生成任何代码。



我已经看到了两个有用的地方。第一种是在不使用函数参数时消除警告:

  #define UNUSED(x)

int foo(int UNUSED(value))
{
return 42;
}

第二个是当您使用条件来确定是否应该有代码

  #ifdef LOGGING_ENABLED 
#define LOG(x)log_message(x)
#else
#define LOG(x)
#endif


If I define a function macro with no actual function, is it like an empty string with the compiler (i.e. It doesn't generate any extra instructions at compile time)?

Example:

#define SomeMacro(a)

SomeMacro("hello"); // This line doesn't add any instructions, does it?

解决方案

You're absolutely correct, the empty macro doesn't generate any code.

I've seen two places where this is useful. The first is to eliminate warnings when a function parameter isn't used:

#define UNUSED(x)

int foo(int UNUSED(value))
{
    return 42;
}

The second is when you use conditionals to determine if there should be code or not.

#ifdef LOGGING_ENABLED
#define LOG(x) log_message(x)
#else
#define LOG(x)
#endif

这篇关于空函数宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆