哪个是在将函数分配给变量或一次又一次调用函数之间使用函数结果的最佳方法?

时间:2015-04-24 12:24:51

标签: c++ variables c++11

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

#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;
}

1 个答案:

答案 0 :(得分:2)

这完全取决于您的功能和代码。如果您的功能是

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

然后我想在某个地方缓存答案,以免多次支付罚款。但是,如果您的函数比性能的最小值更快,那么使用该函数的代码可能比没有函数更具可读性。当然,如果所讨论的功能不纯粹,这个问题没有实际意义。另见memoization。