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 - 3 of 3 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. int main( void )

  2. {

  3.   int a, b = 0;

  4.  

  5.   a = b++; // a == 0, b == 1

  6.   b = 0;

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

  8.  

  9.   b = 0;

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

  11. }

  12.  

  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