In cpp, the result of the following code snippet is: 5 5 5
But in java, the result of the same code snippet is: 3 5 7
I do not know why, is there anyone could explain it?
Thanks a lot!
class H
{
public:
H &pr (int n, char * prompt)
{
cout<<prompt<<n<<" ";
return *this;
}
H &fn(int n)
{
return pr(n,"");
}
};
void test()
{
int v=3;
H h;
h.fn(v).fn(v=5).fn((v=7));
}
Because C++ ain’t Java 🙂
You are mutating the variable
vin the last two function calls. Let’s look at the dissassembly (debug here to see things more clearly, in release a static value of5is used, but it could also be7just as easily. You’ll see why):The order of expression evaluation is not guaranteed to be the order that you call the functions here. You are modifying
vbetween sequence points.7gets assigned tov, then5, then the first function is called. Note that it doesn’t have to be7and then5in that order, it could be swapped! The order of evaluation is unspecified, it could be anything.You have a chain of functions which mutate
vtwice. You cannot count on the fact that each mutation will occur in the order you typed it here.We can simplify it. Let’s say we have two functions;
xandythat both return anint. If I write:There is no guarantee that
x()will be called beforey(). So, if you are mutating an argument common to both functions then the mutation may occur in the call toy()first, which is what you are seeing.