Search code examples
c++compound-assignment

c++ presedence of operators


Hi guys so I need some help understanding how these compound assignment operators work for example

int x=6;
x += x -= x * x;

x turns out to be -60 can someone explain why and how this works?


Solution

  • Ignoring UB with sequence points:

    x += x -= x * x;
    

    is

    (x += (x -= (x * x)));
    

    so

    x * x -> 36

    x -= 36 -> x = -30

    x += -30 -> x = -60