int b=0,a=1;b= ++a + ++a; what is the value of b? what is the calculation for it? [duplicate]

大兔子大兔子 提交于 2019-12-04 07:14:25

问题


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?

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/18078385/int-b-0-a-1b-a-a-what-is-the-value-of-b-what-is-the-calculation-for-it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!