假设在C++(或C,Java等)中我有这样的代码:
int a = f() > g() ? f() : g();
Run Code Online (Sandbox Code Playgroud)
这当然分配一个 F()和g的返回值之间具有较大().现在假设f()和g()本身是复杂而缓慢的,我应该用这样的东西替换这一行
int f_value = f();
int g_value = g();
int a = f_value > g_value ? f_value : g_value;
Run Code Online (Sandbox Code Playgroud)
所以既不F()和G()将被调用两次,或者是编译器(给予足够的优化)会为我做这样的事情呢,所以我没有做任何事情?
当然,这个一般性问题也适用于许多类似的情况.
我试图使用__builtin_return_addressGCC 中的函数来学习一些有关运行时数据结构的基本概念。
我的测试代码是这样的
#include <stdio.h>
void a(int i)
{
if (i>0) {
printf("The return address is %p\n", __builtin_return_address(0) );
a(--i);
}
else
return;
}
int main ()
{
a(10);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出是
The return address is 0x4005ee
The return address is 0x4005db
The return address is 0x4005db
The return address is 0x4005db
The return address is 0x4005db
...
Run Code Online (Sandbox Code Playgroud)
所以我的问题是,为什么那些递归调用的函数的返回地址是一样的,就像它们都返回到顶级调用者一样?它们不应该是“递归直接调用者”之类的东西吗?