-3
int main()
{
    int b=0,a=1;//initialize a and b
    b=++a + ++a;// calculate assign the value of b
    print f("%d",b);
    return 0;
}
  1. what is the value of b?
  2. and what is the calculation for it?
Arijit
  • 17
  • 1
  • 1

2 Answers2

2

This is Undefined Behaviour.Lack of sequence point.

For more info have a look here and output-of-multiple-post-and-pre-increments-in-one-statement.

Community
  • 1
  • 1
Dayal rai
  • 6,548
  • 22
  • 29
0

It would seem that having a sequence point is immaterial in the expression b=++a + ++a;

That is, whether the first ++a is evaluated first or the second ++a is evaluated first in either case a is incremented twice and then the + operator takes effect, so the eventual equation is either b = 2 + 3; or b = 3 + 2 thus b = 5.

When I get home I will try this on with my C compiler.

Blastfurnace's comment about both being evaluated before the + operator takes effect is correct, and now that I think about it, obvious.

That is, + is lower in precedence than ++a. It could be argued that this statement is NOT ambiguous in that switching the order of evaluation (R to L or L to R, both with respect to precedence) results in the same answer.

No one will claim this is well written code, interesting on several points for a discussion, but not something that should be endorsed.

JackCColeman
  • 3,777
  • 1
  • 15
  • 21
  • ...or both side are evaluated before the addition and the result is `3 + 3`. Either way this code is awful and there is no point trying to reason about it. – Blastfurnace Aug 07 '13 at 00:25
  • in my c compiler the value of b is showing is 6. here a single memory named "a" is shared for both times. for first ++a the vale of a = 2 and for 2nd ++a ,a=3 then b=3+3=6. – Arijit Sep 29 '13 at 14:22
  • @Arijit, I agree, after actually trying it. – JackCColeman Sep 29 '13 at 19:53