-1

Code:

{
  int a =2,b=2,c=0;
  c = a+(b++);

  printf("output:c=%d\tb=%d\n",c,b);
}

Output:

output: c=4      b=3

How output of c = 4 here, My understanding is c=5, can any one explain it please?

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173

2 Answers2

3

Because there is a difference between ++i and i++!

Prefix/ Postfix

++i  // `Prefix` gets incremented `before` it get's used (e.g. in a operation)
i++  // `Postfix` gets incremented `after` it get's used (e.g. in a operation)

So that's why c is 4!

If you change b++ to ++b then c gets 5!

See also:

What is the difference between prefix and postfix operators?

Community
  • 1
  • 1
Rizier123
  • 58,877
  • 16
  • 101
  • 156
2

I don't think b++ is quite doing what you think it is. c = a+(b++) says "c equals a plus b then increment b by one", therefore c will be 4. If you use ++b instead, b will be incremented before the addition and c will be 5.

c = a+(b++); // c = 4
c = a+(++b); // c = 5

After each of these lines b will be 3, the only thing that changes between them is when b becomes 3.

Tim B
  • 3,033
  • 1
  • 23
  • 28