ric*_*ard 7 c gcc c-preprocessor
我想定义一个像MACRO这样的函数.即
#define foo(x)\
#if x>32\
x\
#else\
(2*x)\
#endif
Run Code Online (Sandbox Code Playgroud)
那是,
if x>32, then foo(x) present x
else, foo(x) present (2*x)
Run Code Online (Sandbox Code Playgroud)
但我的海湾合作委员会抱怨:
int a = foo(31);
Run Code Online (Sandbox Code Playgroud)
我认为C预处理器应该正确处理.因为在编译时,它知道x=33.它可以代替foo(33)用(2*33)
Joh*_*itb 13
你可以如下
#define foo(x) ((x) > 32 ? (x) : (2 * (x)))
Run Code Online (Sandbox Code Playgroud)
但是这次评估x多次.您可以改为创建一个更干净的静态函数
static int foo(int x) {
if(x > 32)
return x;
return 2 * x;
}
Run Code Online (Sandbox Code Playgroud)
然后你也可以传递foo有副作用的东西,副作用只发生一次.
什么你写使用的#if,#else和#endif预处理指令,但你需要,如果你传递变量的宏观和要评估他们的价值使用的语言结构.在实际语言结构中使用if和else语句也不起作用,因为控制流语句不会计算为值.换句话说,if语句只是转向控制流("如果A,则执行B,否则执行C"),而不是评估任何值.
#define \
foo(x) \
({ \
int xx = (x); \
int result = (xx > 32) ? xx : (2*xx); \
result; \
})
Run Code Online (Sandbox Code Playgroud)