C++执行宏观时没有得到预期的结果

发布于 2025-02-02 03:12:29 字数 246 浏览 6 评论 0原文

#include <stdio.h>
#define swapOut(a,b) a+b-a, a+b-b

int main()
{
    int a = 5;
    int b = 6;

    printf("%d,%d", swapOut(a+b,b-a));
    
    return 0;
}

执行此程序时,我希望输出为“ 1,11”,但实际输出为“ 13,1”。有人可以解释这里发生了什么吗?

#include <stdio.h>
#define swapOut(a,b) a+b-a, a+b-b

int main()
{
    int a = 5;
    int b = 6;

    printf("%d,%d", swapOut(a+b,b-a));
    
    return 0;
}

When executing this program, I am expecting the output to be "1,11", but the actual output is "13,1". Can someone explain what is happening here ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

痴情换悲伤 2025-02-09 03:12:29

要了解正在发生的事情,您必须意识到宏不像功能。他们执行非常简单的文字替代。因此,当您定义

#define swapOut(a,b) a+b-a, a+b-b

并将其用作交换(A+B,BA)时,将其扩展为a+b+b+ba-a+b,a+b+baba 。使用值a = 5b = 6这在13,1中导致。

因此,这是一个有价值的教训:始终用括号中的宏中围绕宏的论点。您程序的更正版本是

#include <stdio.h>
#define swapOut(a,b) ((a)+(b)-(a)), ((a)+(b)-(b))

int main()
{
    int a = 5;
    int b = 6;

    printf("%d,%d", swapOut(a+b,b-a));

   return 0;
}

您预期的,这确实是输出1,11

To understand what's happening, you have to realise that macros are not like functions; they perform very simple text substitution. Thus, when you define

#define swapOut(a,b) a+b-a, a+b-b

and then use it as swapOut(a+b,b-a), it is expanded as a+b+b-a-a+b, a+b+b-a-b-a. With the values a=5 and b=6 this results in 13,1.

So here's a valuable lesson: always surround the arguments in macros with parentheses. The corrected version of your program is

#include <stdio.h>
#define swapOut(a,b) ((a)+(b)-(a)), ((a)+(b)-(b))

int main()
{
    int a = 5;
    int b = 6;

    printf("%d,%d", swapOut(a+b,b-a));

   return 0;
}

This indeed outputs 1,11 as you expected.

小姐丶请自重 2025-02-09 03:12:29

为了实现这一目标,您必须先定位该值。

#include <stdio.h>
#define swapOut(a,b) a+b-a, a+b-b

int main()
{
    int a = 5;
    int b = 6;
    int c = a + b;
    int d = b - a;
    
    printf("%d,%d", swapOut(c,d));
    
    return 0;
}

To achieve this, you have to localize the value first.

#include <stdio.h>
#define swapOut(a,b) a+b-a, a+b-b

int main()
{
    int a = 5;
    int b = 6;
    int c = a + b;
    int d = b - a;
    
    printf("%d,%d", swapOut(c,d));
    
    return 0;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文