Issue
My question can be pointed out regarding any programming language, but I wanna know regarding C++. I want to know where the intermediate value will store in C++? For example in the below code:
int func1(int);
int func2(int);
int func3(int);
int main(){
int a = 10;
int b = func1(func2(func3(a)));
cout<<b<<endl;
}
where the return value of func3 will be stored? What about func2? Will it store in CPU cache? or Ram?
Also, regarding the below code where the result of a*b
will be stored? Or any intermediate values:
int main(){
int a = 10;
int b = 15;
int c = a*b+10*15;
cout<<c<<endl;
}
If it is compiler dependent, please explain regarding any compiler, especially GCC.
Solution
Since you only declared the function I will assume they are in separate compilation units. So the compiler has to generate a function call for them. No inlineing or specialization of the functions possible (lookup link time optimization for how that isn't always true).
The way functions are called, arguments are passed and and returned is defined in the calling convention for the architecture and ABI you are targeting. So this isn't compiler specific as object files from different compilers are supposed to be compatible if they follow the same ABI.
So this governs what happens in each function call taken on it's own. In between the function calls the values can be stored on the stack or in registers but generally compilers try to do the minimal amount of work to get things from where one function returns them to where the next function expects them.
PS: If the compiler sees the definition of the functions then all bets are of. It can do whatever it likes as long as no change is observable by the program itself.
Answered By - Goswin von Brederlow Answer Checked By - David Marino (WPSolving Volunteer)