Assignment operator chain understanding

前端 未结 2 917
攒了一身酷
攒了一身酷 2021-02-11 10:45

Can some one explain the output of below code

int a=10;
a = a -= a+= a -= a += a;

output : 10 

I am not able to get how it is giving 10?

2条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-11 11:31

    a += a means a = a + a.

    likewise, a -= a means a = a - a.

    I am not sure which way is proper to start, but if I convert the given code from the right using above,

       a += a                     >     a = a + a;
       a -= a += a                >     a = a - (a + a);
       a+= a -= a += a            >     a = a + (a - (a + a ));
       a -= a+= a -= a += a       >     a = a - (a + (a - (a + a)));
       a = a -= a+= a -= a += a   >     a = a - a - a + a + a;
    

    where -a -a + a + a cancels each other, resulting a = a, which is 10.

提交回复
热议问题