Assignment operator chain understanding

前端 未结 2 1933
执念已碎
执念已碎 2021-02-11 10:56

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:16

    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.

提交回复
热议问题