C宏,带有表达式不必要的结果 [英] C macro with expression unwanted result
问题描述
我正在运行以下程序并获得9 7的结果,我理解为什么9是输出,但是我不知道为什么我得到7作为输出.
I am running the following program and getting a result as 9 7, I understood why 9 is the output but I can't figure out why I'm getting 7 as output.
#include<stdio.h>
#define sqr(i) (i*i)
int main()
{
printf("%d %d", sqr(3), sqr(3+1));
return 0;
}
第二个功能是sqrt(3+1)
微型如何扩展以及我如何获得7输出?
For the second function that is sqrt(3+1)
how the micro is getting expanded and how Im getting 7 output?
推荐答案
您可以让编译器或IDE对文件进行预处理,并向您展示宏的扩展方式.
You can have the compiler or IDE preprocess the file and show you how the macro expanded.
在您的情况下,sqr(3+1)
扩展为(3+1*3+1)
.现在,C运算符的优先级意味着乘法在加法之前完成.所以(3+1*3+1)
-> (3+3+1)
-> (7)
.
In your case sqr(3+1)
expands to (3+1*3+1)
. Now the precedence of C operators means that the multiplication is done before the addition. So (3+1*3+1)
-> (3+3+1)
-> (7)
.
您可以通过以下方式定义宏来解决此问题,并在参数周围加上括号:
You can fix this by defining your macro this way, with parentheses around the argument:
#define sqr(i) ((i)*(i))
这篇关于C宏,带有表达式不必要的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!