求助编译灵异事件
  • 板块学术版
  • 楼主c1120241919
  • 当前回复6
  • 已保存回复6
  • 发布时间2023/5/25 17:39
  • 上次更新2023/10/23 14:48:07
查看原帖
求助编译灵异事件
686053
c1120241919楼主2023/5/25 17:39

RT,在一份代码中遭遇了一个关于函数返回值的问题:

#include<bits/stdc++.h>
using namespace std;
struct Tree{int lc,rc;};
int tot;
vector<Tree> lzh;
inline int ZHA(){
    ++tot;
    lzh.resize(tot+1);
    return tot;
}
#define push_down(x){\
    if(lzh[x].lc==0)lzh[x].lc=ZHA();\
    if(lzh[x].rc==0) lzh[x].rc=ZHA();\
}
signed main(){
    lzh.resize(2);tot=1;
    push_down(1);
    for(int i=1;i<=tot;i++)
    printf("%d:lc=%d,rc=%d\n",i,lzh[i].lc,lzh[i].rc);
    return 0;
}

这份代码使用的函数,输出为:

1:lc=0,rc=3
2:lc=0,rc=0
3:lc=0,rc=0

而另外一份 define 的代码:

#include<bits/stdc++.h>
using namespace std;
struct Tree{int lc,rc;};
int tot;
vector<Tree> lzh;
#define ZHA() (++tot,lzh.resize(tot+1),tot)
#define push_down(x){\
    if(lzh[x].lc==0)lzh[x].lc=ZHA();\
    if(lzh[x].rc==0) lzh[x].rc=ZHA();\
}
signed main(){
    lzh.resize(2);tot=1;
    push_down(1);
    for(int i=1;i<=tot;i++)
    printf("%d:lc=%d,rc=%d\n",i,lzh[i].lc,lzh[i].rc);
    return 0;
}

输出为:

1:lc=2,rc=3
2:lc=0,rc=0
3:lc=0,rc=0

后面一种是需要的正确输出。

我们现在想知道,为什么通过函数返回得到的值是错误的?

上述代码在 NOI Linux 下运行,g++ 编译出来第一种挂了,但用 clang 两个都可过。

2023/5/25 17:39
加载中...