Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/153.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在将函数结果赋给变量或反复调用函数之间,使用函数结果的最佳方法是什么?_C++_Variables_C++11 - Fatal编程技术网

C++ 在将函数结果赋给变量或反复调用函数之间,使用函数结果的最佳方法是什么?

C++ 在将函数结果赋给变量或反复调用函数之间,使用函数结果的最佳方法是什么?,c++,variables,c++11,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

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

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

然后我想把答案存储在某个地方,这样就不会多次支付罚款。但是,如果您的函数比最低性能标准快,那么使用该函数时代码的可读性可能比不使用该函数时更高。当然,如果所讨论的函数不是纯函数,那么这个问题是没有意义的。另请参阅备忘录。

当您比较两种版本的测量结果时,您发现了什么?