#定义Square(x)(x *(x)) [英] #define Square(x) (x*(x))
本文介绍了#定义Square(x)(x *(x))的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
$ b定义的数字的平方$ b
能否请您解释以下代码为何输出 29?
Can you please explain why the following code outputs "29"?
#define Square(x) (x*(x))
void main()
{
int x = 5;
printf("%d", Square(x+3));
}
推荐答案
由于宏仅用于文本替换您最终得到:
Since macros only do textual replacement you end up with:
x + 3 * (x + 3)
这是29。
您绝对应该始终在括号之间放置宏参数。
You should absolutely always put macro arguments between parentheses.
#define Square(x) ((x)*(x))
更好的方法是使用函数并信任编译器对其进行内联。
Better yet, use a function and trust the compiler to inline it.
EDIT
正如leemes所说,宏两次评估 x
的事实是一个问题。使用功能或更复杂的机制(例如gcc语句表达式)可以解决此问题。这是一个笨拙的尝试:
As leemes notes, the fact that the macro evaluates x
twice can be a problem. Using a function or more complicated mechanisms such as gcc statement expressions can solve this. Here's a clumsy attempt:
#define Square(x) ({ \
typeof(x) y = (x); \
y*y; \
})
这篇关于#定义Square(x)(x *(x))的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文