在算术前pression的背景下宏观扩张? [英] Macro expansion in context of arithmetic expression?

查看:101
本文介绍了在算术前pression的背景下宏观扩张?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网站上看到这个低于code。
我能不能understsnd结果是如何来为 11 ,而不是 25 13

为什么我想到的是 25 ,因为 SQ(5)5 * 5

13 ,因为

SQ(2)= 4;

SQ(3)= 9;

可能是最终的结果将是 13(9 + 4)
但是,惊讶地看到作为结果 11
如何将结果作为未来 11

 使用命名空间std;
的#define SQ(一)(A * A)
诠释的main()
{
    INT ANS = SQ(2 + 3);
    COUT<< ANS&LT​​;< ENDL;
系统(暂停);
}


解决方案

的#define 扩张踢编译器看到源$ C ​​$ C之前。这就是为什么他们被称为的 pre-处理器指令的,这里的处理器是转换C到机器可读code编译器。

所以,这就是宏pre-处理器传递到编译器:

SQ(2 + 3)被扩展为(2 + 3 * 2 + 3)

所以,这是真的 2 + 6 + 3 = 11

你怎么可以把它做你的期望?


  1. 实施评估的顺序。使用(),无论是在宏定义或宏调用。
    OR

  2. 写一个简单的函数,没有工作

I saw this below code in an website. I could not able to understsnd how the result is coming as 11, instead of 25 or 13.

Why I am thinking 25 because SQ(5) 5*5

or 13 because

SQ(2) = 4;

SQ(3) = 9;

may be final result will be 13 (9 + 4) But surprised to see result as 11. How the result is coming as 11?

using namespace std;
#define SQ(a) (a*a)
int main()
{
    int ans = SQ(2 + 3);
    cout << ans << endl;
system("pause");
}

解决方案

#define expansions kick in before the compiler sees the source code. That is why they are called pre-processor directives, the processor here is the compiler that translates C to machine readable code.

So, this is what the macro pre-processor is passing on to the compiler:

SQ(2 + 3) is expanded as (2 + 3*2 + 3)

So, this is really 2 + 6 + 3 = 11.

How can you make it do what you expect?

  1. Enforce the order of evaluation. Use (), either in the macro definition or in the macro call. OR
  2. Write a simple function that does the job

这篇关于在算术前pression的背景下宏观扩张?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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