Priority Expression? How does this happen?

In cpp, the result of the following code snippet is: 5 5 5 But in java, the result of the same code snippet: 3 5 7 I don't know why, can anyone explain this? Many thanks!

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));
}
+5
source share
2 answers

In cpp, the result of the following code fragment is: 5 5 5 But in java, the result of the same code fragment: 3 5 7 I don’t know why,

Because C ++ is not Java :)

You mutate a variable vin the last two function calls. Let's look at the disassembler (debugging here to see something more clearly, the release uses a static value 5, but it can also be 7just as easy. You will see why):

    h.fn(v).fn(v=5).fn((v=7));
00411565  mov         dword ptr [v],7 
0041156C  mov         dword ptr [v],5 
00411573  mov         eax,dword ptr [v] 
00411576  push        eax  

, . v . 7 v, 5, . , 7, 5 , ! , .

, v . , , .

. , ; x y, a int. :

int k = x() + y();

, x() y(). , , , y() , , .

+6

, , .

, , , ,

warning: operation on ‘v’ may be undefined

, : ?

+2

All Articles