coperatorsassignment-operatorpre-increment

Usage of '+=' in c


I don't understand why, on this code, 'b+=' return 6 instead of 5. The operation on right-end of operator '+=', should be 0.

  1. i/2 = 4
  2. a-4= 0

So Operator '+=' should just add: 0.

#include<stdio.h>

int main(){
  int a=4, i=8;
  int b;
  
  b=++a; 
  printf("%i\n",b);

  b+=a-i/2;
  printf("%i\n",b);

}

Just using theory of sintax


Solution

  • After this statement

    b=++a;
    

    b and a will be equal to 5 due to the prefix increment operator ++.

    From the C Standard (6.5.3.1 Prefix increment and decrement operators)

    2 The value of the operand of the prefix ++ operator is incremented. The result is the new value of the operand after incrementation. The expression ++E is equivalent to (E+=1)

    So in this compound assignment statement

    b+=a-i/2;
    

    that may be rewritten like

    b = b + a - i/2;
    

    you have

    b = 5 + 5 - 4
    

    So as a result you have b is equal to 6.

    You could get the expected by you result if to initialize the variable b by zero

    int b = 0;
    

    and if to remove this statement

    b=++a;