I'm mostly interested in C and C++, but I think this question can also apply to other languages.
My question is, if an unamed object or value is generated from the evaluation of an expression or function, can it be cached if that same expression or function is later called, and the compiler recognizes that the result is unchanged.
Demonstrated in the below examples
x=(a+b)/c;
y=(a+b)/c;
a+=x;
z=(a+b)/c;
and
int my_function()
{
return (a+b)/c;
}
int main()
{
x=my_function();
y=my_function();
a+=x;
z=my_function();
}
The compiler will cache the result of the expression (a+b)/c, or the function my_function when assigning x, and change the assignments of y to a reference to the cached result, without the calculation or function having to be performed again. But since their is a visible change to that expression or function with a+=x, z is assigned by reevaluating (a+b)/c, or calling my_function a second time.
This question also applies to larger data types, like structs and classes, which I imagined could be assigned to the current stack frame like local variables, but unnamed and not directly accessible by the programmer.
While typing this, I saw another question asking the same thing about Python, referencing the C++ standard, which stated that a temporary object does not last after the statment it is created in.
https://stackoverflow.com/questions/9046606/are-temporary-references-automatically-cleared-in-python
So, my question is, even if that object no longer exists within the rules of the language, can it still be retained by the the compiler as a form of optimization, if it detects that within the rules of the language the same evaluation or function call will yield the same result.
I want to effectively treat a function call or expression like a stored variable in situations where I know it will return the same result, without it performing the evaluation or function call each time. Do I have to assign the result to a named variable to achieve this.
The compiler I am using is GCC.