Difference between b++ and b=b+1

What is the difference between b++ and b=b+1?
Which one is more used and why?

Questions by sushila sonare   answers by sushila sonare

Showing Answers 1 - 1 of 1 Answers

The main differences between `b++` and `b = b + 1` is that in the first case, `b` is only evaluated once, and the result of the first expression is the value of `b` *before* the increment.
`b++` evaluates to the current value of `b`, and as a *side effect* increments `b`. `++b` evaluates to the current value of `b` plus 1, and as a side effect increments `b`. See code snippet for examples.
In an expression like `a = b++`, its not guaranteed that `b` is incremented before `a` is assigned; the operations are *unsequenced* relative to each other. C does not force left-to-right evaluation in most cases, nor does it require that the side effect of the `++` operator be applied immediately after evaluation. This means that expressions of the form `b++ * b++` or `a[i] = i++` or similar invoke *undefined behavior* - youre not guaranteed of getting the result you expect.

Code
  1. span style="font-style: italic;">// a == 0, b == 1

  2.   b = 0;

  3.   a = ++b; // a == 1, b == 1

  4.  

  5.   b = 0;

  6.   a = b = b + 1; // == a = (b = b + 1), a == 1, b == 1

  7. }

  8.  

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions