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;
}
- what is the value of b?
- and what is the calculation for it?
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;
}
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.
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.