Why is the return value not what I expected in this C program with macro? [duplicate]

こ雲淡風輕ζ 提交于 2020-01-30 11:40:06

问题


When I run the following code, the return value is 11, but I was expecting it to return 25. Can someone explain this?

#include<stdio.h>
#define SQR(a) a*a

int main()
{
    int i=3;
    printf("%d",SQR(i+2));
    return 1;
}

回答1:


Needs more parentheses. This:

#define SQR(a) a*a

expands to this:

i+2*i+2

which is:

3+2*3+2

which is 11 because * has precedence over +.

You need to define your macro like this:

#define SQR(a) ((a)*(a))

to ensure that this kind of thing doesn't happen.




回答2:


Macros are not the same as regular functions.

During the reprocessing all macros are replaced exactly by what they are define. In your case, the line:

 printf("%d",SQR(i+2));

is replaced by the line:

 printf("%d", i+2*i+2);

So, you see the unexpected result there.

The correct way is:

#define SQR(a) ((a)*(a))

The preprocessor result will be:

printf("%d", ((i+2)*(i+2)));

Try to learn on this mistake. Issues of this kind are quite hard to debug.



来源:https://stackoverflow.com/questions/18557321/why-is-the-return-value-not-what-i-expected-in-this-c-program-with-macro

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!