这将是在将函数分配给变量或一次又一次地调用函数之间使用函数结果的最佳方式

which will the best way to use the result of function between assigning it to a variable or calling the function again and again?

本文关键字:函数 之间 结果 方式 最佳 调用 一次又一次 分配 变量      更新时间:2023-10-16

我有一个将返回值的函数,我想在多个地方使用该函数的结果。将结果存储到变量并在我想要的地方使用它,或者一次又一次地直接调用该函数,而不是将其存储在变量中并使用它。

#include<iostream>
int function(int x,int y){
  return (x<<y);
}
int main(){
  int a = 10;
  int b = 5;
  int c = function(a,b);
  int d = c*c; 
  int e =function(a,b)*function(a,b);
  return 0;
}

这完全取决于你的函数和代码。如果您的函数是

struct DeepThought {
    int theAnswer() {
        sleep(7.5 million years);
        return 42;
    }
};

那么我想将答案缓存在某个地方,以免多次支付该罚款。但是,如果您的函数比性能的最低标准快,则使用该函数的代码可能比不使用函数时更具可读性。当然,如果所讨论的函数不是纯粹的,那么这个问题就没有意义了。另请参阅记忆。