0

Possible Duplicate:
Post Increment and Pre Increment concept?

Can any one explicitly explain how prefix increment differs from suffix increment?

also can someone explain why this output 6?

i=1;
cout << ++i + ++i;

also why this gives 4

i = 1;
cout << ++i + i++;

and why this produces true

i = 0;
cout << (i++ || i++)
Community
  • 1
  • 1
user1741485
  • 181
  • 3
  • 3
  • 7
  • 2
    case 1 I think it should be 5 not 6. – jaisonDavis Oct 12 '12 at 15:53
  • also http://stackoverflow.com/questions/12551576/pre-increment-and-post-increment – bames53 Oct 12 '12 at 15:53
  • 2
    I think you may benefit from doing some more background reading about c/c++. The code you have specified where more than one increment is applied to the same variable is unspecified behaviour. That means that the compiler can do what it wants. This is not always what you expect. – Will Oct 12 '12 at 15:54
  • 1
    Why write code that you need to scratch your head to figure out what is going on? Just leads to problems in the future for either yourself or another programmer. Code should be readable. – Ed Heal Oct 12 '12 at 15:55
  • Since this question concerns sequence points and undefined behavior, I think this is a better duplicate: http://stackoverflow.com/questions/949433/could-anyone-explain-these-undefined-behaviors-i-i-i-i-i-etc – Thomas Padron-McCarthy Oct 12 '12 at 15:59
  • @Will with the exception of the last, `cout << (i++ || i++)` is kosher, there's a sequence point after the evaluation of the first operand of `(||)` [the lingo changed, nowadays, the evaluation of the first operand of `(||)` is sequenced before the evaluation of the second]. – Daniel Fischer Oct 12 '12 at 19:15

2 Answers2

3

The prefix ++i and suffix i++ operators affect the order in which the statement is evaluated. With the prefix ++i, the value of i is incremented, and that is what is used. But with the suffix i++, the original value of i is used, and then it is incremented for anything following that line.

Rivasa
  • 6,510
  • 3
  • 35
  • 64
3

1) Pretty obviously, "++i" increments the variable first, and "i++" increments afterward.

2) Less obviously, complex expressions mixing infix increment/decrement with other operations on the same variable can introduce undefined behavior:

I agree: the thread Post-increment and Pre-increment concept? addresses this question.

Community
  • 1
  • 1
paulsm4
  • 114,292
  • 17
  • 138
  • 190