在C函数类的宏定义 [英] Function-like macro definition in C

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

问题描述

我想这样定义宏功能。即。

I'd like to define a function like MACRO . i.e.

#define foo(x)\
#if x>32\
 x\
#else\
 (2*x)\
#endif

这就是

if x>32, then foo(x) present x
else, foo(x) present (2*x)

但我的GCC抱怨:

but my GCC complains about:

int a = foo(31);

我认为C preprocessor应该正确地处理这个问题。因为在编译的时候,它知道 X = 33 。它可以取代富(33)(2 * 33)

推荐答案

可以如下:

#define foo(x) ((x) > 32 ? (x) : (2 * (x)))

不过,其值 X 多次。您可以改为创建一个静态函数,它是清洁

But that evaluates x multiple times. You can instead create a static function, which is cleaner

static int foo(int x) {
  if(x > 32) 
    return x;
  return 2 * x;
}

那么你也能够通过事有副作用,而且有副作用只发生一次。

Then you are also able to pass things to foo that have side effects, and have the side effect happen only one time.

什么你写使用#如果的#else #ENDIF preprocessor指令,但你需要的,如果你传递变量的宏观和要评估他们的价值使用的语言结构。使用如果其他语句,在实际的语言结构没有任何工作,因为控制流语句不要 ŧ评估为价值。换句话说,一个if语句转向控制流量只有(如果A,然后执行B,否则执行C),不评价任何值。

What you have written is using the #if, #else and #endif preprocessor directives, but you need to use language constructs if you pass variables to the macro and want to evaluate their values. Using if, and else statements as in the actual language constructs don't work either, because control flow statements don't evaluate to values. In other words, an if statement is steering control flow only ("if A, then execute B, else execute C"), not evaluating to any values.

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

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