0

why the Increment operator is working weird?

If int b = 2;

and b = b++ + b++ + b++; //output is 9

Then why b = b++ + b++; //output is 5

and not 6???

Meezan Malek
  • 110
  • 1
  • 5
  • This is undefined behaviour. Any result is possible. You may not both assign and increment the same variable. – Max Oct 31 '22 at 15:27
  • 1
    `b++` returns the old value, and then increments the variable. `++b` increments the value, then returns the new value. When you do `b++ + b++`, you'll typically see the first `b++` evalulate to `2` (and increment `b` to `3`), and the second evaluate to `3` (and increment `b` to `4`). However, this is still undefined behavior, and won't always be the case. – Rogue Oct 31 '22 at 15:28

0 Answers0