Reputation:
Consider the code:
#include<iostream>
using namespace std;
int refcube(double &ra)
{
ra*=ra*ra;
return ra;
}
int main()
{
auto x=2.0;
cout<<"cube of "<<x<<" is "<<refcube(x)<<endl;
return 0;
}
The output is:
cube of 8 is 8
Why the value of x
at the first is displaying as 8
instead of 2
?
Upvotes: 0
Views: 36
Reputation: 118292
Because evaluation order is not specified.
The compiler may generate the code to call refcube(x)
and compute its value before or after generating the code to obtain the value of x
, for output to std::cout
.
Your compiler chose to compile this C++ code as calling refcube(x)
first, and then by evaluating x
.
The C++ language specification spends quite a few pages on the topic of "sequencing", which (very loosely speaking) specifies the evaluation order. To make a long story short, in this example, x
is not sequenced with respect to refcube(x)
, in the expression that generates the output to std::cout
, and such a compiler is free to compile either portion of the expression first.
Upvotes: 3