Why is the return value not what I expected in thi

2020-05-01 07:14发布

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;
}

标签: c macros printf
2条回答
我命由我不由天
2楼-- · 2020-05-01 07:47

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.

查看更多
趁早两清
3楼-- · 2020-05-01 07:55

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.

查看更多
登录 后发表回答