假设我有以下代码:
int f() {
int foo = 0;
int bar = 0;
foo++;
bar++;
// many more repeated operations in actual code
foo++;
bar++;
return foo+bar;
}
将重复的代码抽象为一个单独的函数,我们得到
static void change_locals(int *foo_p, int *bar_p) {
*foo_p++;
*bar_p++;
}
int f() {
int foo = 0;
int bar = 0;
change_locals(&foo, &bar);
change_locals(&foo, &bar);
return foo+bar;
}
我希望编译器能够内联change_locals
函数,并将*(&foo)++
生成的代码中的内容优化为foo++
.
如果我没记错的话,获取局部变量的地址通常会阻止一些优化(例如,它不能存储在寄存器中),但是当没有对地址进行指针运算并且它没有从函数中转义时,这是否适用?使用更大的change_locals
,如果它被声明inline
(__inline
在 MSVC 中)会有所不同吗?
我对 GCC 和 MSVC 编译器的行为特别感兴趣。