1

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

I have an expression in a program, initial value of i = 10

int j = i++ + i++;

it sets j as 20 but

int j = i++ + ++i;

it sets j as 22
Why is there a difference of two between statements? I think, difference should be of 1.
I know this is undefined in C, but why GCC is doing such things?

Community
  • 1
  • 1
neel
  • 8,399
  • 7
  • 36
  • 50
  • 1
    Why do you think the difference should be 1? – David Brown Oct 28 '12 at 20:08
  • 1
    What part of "undefined" do you want us to define for you? – Kerrek SB Oct 28 '12 at 20:09
  • 1
    @DavidBrown: maybe someone could think the difference should be 1 because he can't find a "consistent behavior" that evaluates the first expression to 20 and the second to 22, and/or why a compiler would choose that way, what are the benefits... – effeffe Oct 28 '12 at 20:12
  • in first statement, value of first i++ should be 10 and second i++ should use 11, I think. So it should give 21. If it is incorrect, then how values are used in second statemnet – neel Oct 28 '12 at 20:12
  • 1
    Closed as exact duplicate? Why? I can't see the same question, nor the answer to this question in the accepted answer of the possible duplicate. – effeffe Oct 28 '12 at 20:19
  • 2
    @neel what if `++i` is evaluated first? – David Brown Oct 28 '12 at 20:21
  • 1
    Why do people close questions and never come back again to read comments? I don't think this is a nice use of rep, it's like downvote without a comment to explain why... – effeffe Oct 28 '12 at 20:32
  • @DavidBrown because postincrement has higher priority then preincrement – neel Oct 28 '12 at 21:21
  • @neel It has to do with the order in which the operands of `+` are evaluated. If the right argument is evaluated first it will be 22. However in C the order of evaluation of the operands is unspecified. – David Brown Oct 28 '12 at 21:45
  • @DavidBrown but according to precedence of operators postincrement will happen first then preincrement and then addition. – neel Oct 28 '12 at 21:48
  • @neel: no, operator precedence doesn't apply here. It would in an expression like "++i++" (if that was well-defined). Nothing defines which operand (`a` or `b`) is evaluated first in `a + b`, regardless of what a and b are (plain constants or complex expressions). – Mat Oct 29 '12 at 06:14

1 Answers1

-1

For i++ it is like: first do the equation then increment i.

For ++ i is like: first increment i then do the equation.

so i guess i++ + ++i is interpreted as i + (++(++i)) so thats the result is 22.

Wired things happen with wired syntax just dont do stuff like this ;).

If i'm right ++i + ++i would be 22 also.

C. Holzberger
  • 318
  • 2
  • 4