为什么返回值不是我所期待的宏观此C程序? [英] Why is the return value not what I expected in this C program with macro?

查看:98
本文介绍了为什么返回值不是我所期待的宏观此C程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我运行下面的code,返回值是11,但我期待它返回25.有人能解释一下吗?

 #包括LT&;&stdio.h中GT;
#定义SQR(A)A * A诠释的main()
{
    INT I = 3;
    的printf(%d个,SQR(I + 2));
    返回1;
}


解决方案

需要更多的括号内。这样的:

 的#define SQR(A)A * A

扩展到这一点:

  I + 2 * I + 2

这是:

  3 + 2 * 3 + 2

这是因为11 * 拥有超过precedence +

您需要定义这样的宏:

 的#define SQR(A)((A)×(A))

要确保这种事情不会发生。

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

解决方案

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.

这篇关于为什么返回值不是我所期待的宏观此C程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆