简体   繁体   English

C宏,带有表达式不必要的结果

[英]C macro with expression unwanted result

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. 我正在运行以下程序,并得到9为7的结果,我理解了为什么9是输出,但我不知道为什么我得到7作为输出。

#include<stdio.h>
#define sqr(i) (i*i)

int main()
{
    printf("%d %d", sqr(3), sqr(3+1));
    return 0;
}

For the second function that is sqrt(3+1) how the micro is getting expanded and how Im getting 7 output? 对于第二个函数sqrt(3+1)如何扩展微型以及如何获得7输出?

You can have the compiler or IDE preprocess the file and show you how the macro expanded. 您可以让编译器或IDE对该文件进行预处理,并向您展示宏的扩展方式。

In your case sqr(3+1) expands to (3+1*3+1) . 在您的情况下sqr(3+1)扩展为(3+1*3+1) Now the precedence of C operators means that the multiplication is done before the addition. 现在,C运算符的优先级意味着乘法在加法之前完成。 So (3+1*3+1) -> (3+3+1) -> (7) . 所以(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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM