0

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

ikegami
  • 367,544
  • 15
  • 269
  • 518

2 Answers2

4

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;

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

When you execute b=++a;, a is incremented. Its value becomes 5. Then afterward, a-i/2 is 5-8/2 then 1.

Frédéric LOYER
  • 1,064
  • 5
  • 10