【发布时间】:2016-04-26 21:36:50
【问题描述】:
为什么接下来的 2 个代码段之间存在差异:
struct g {
int m[100];
};
struct a {
struct g ttt[40];
struct g hhh[40];
}man;
extern int bar(int z);
//this code generate a call to memcopy.
void foo1(int idx){
bar(((idx == 5) ? man.hhh[idx+7] : man.ttt[idx+7]).m[idx+3]);
}
//this code doesn't generate a call to memcopy.
void foo2(int idx){
bar(((idx == 5) ? man.hhh[idx+7].m[idx+3] : man.ttt[idx+7].m[idx+3]));
}
在两个代码段中,我想将相同的字段(取决于条件表达式)发送到 bar 函数。但是,第一个代码会生成对 memcopy 的调用(当使用 clang 编译到 powerpc arch 时,可以清楚地看到)。我写了一点 main 并运行了 2 个函数,它们给了我相同的输出(使用 gcc 4.4.7 编译)。
【问题讨论】:
-
将 struct 转换为 int?
-
请选择您使用的语言对应的语言标签
-
在第一个sn-p中,条件表达式的结果类型为
struct g。编译器使用memcpy复制该结果。在第二个 sn-p 中,条件表达式的结果类型为int。编译器可以使用mov指令复制该结果。所以避免使用第一个 sn-p,反正第二个 sn-p 更容易阅读。
标签: c