-4

Possible Duplicate:
Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…)

I have this code but i'm not getting how its functioning.

main()
{
 int i=1;
 i= ++i + ++i + ++i;
 printf("%d",i);
}

I tried to compile it and im getting the output 10 but i've no idea how. What I figured out is the two ++i are getting assigned the value 3 and the one ++i is getting the value 4, before the addition operation is performed. I cant figure out how increment operator is working in this case. Plz help me out with this.

Community
  • 1
  • 1
pratZ
  • 2,808
  • 1
  • 17
  • 28

2 Answers2

1

The behavior is undefined .. there are a lot of posts similar to this if you search on SO.

For instance What would the evaluation order of x = x++ + ++x; be? or Why are these constructs (using ++) undefined behavior? and more.

Finally, just an opinion/comment: I don't think anyone would advocate writing that type of code as it's also hard to understand (hence the reason for your question).

Community
  • 1
  • 1
Levon
  • 129,246
  • 33
  • 194
  • 186
0

I'm pretty sure you're not supposed to do that. Basically, don't modify a value more than once inside of the same expression. To do otherwise invokes "undefined behavior", which is a fancy way of saying "the compiler makes no guarantees of what will happen.

(Technically, the rule is don't modify a value more than once between the same sequence points)

jkerian
  • 15,631
  • 3
  • 44
  • 57