-2

In order to find out what happened at the expression "i++ + i++ + i++ + i++", I wrote a test program as below. test program source code

compile it with g++ 4.6.3 and running this program under Ubuntu 12.04, the result are:

        construct 3
        construct 7
        construct 12
        construct 18
        construct novalue
        call i++ for 18
        call i++ for 12
        call i++ for 7
        call i++ for 3
        call + for 3 and 7
        call + for 10 and 12
        call + for 22 and 18
        i1++ + i2++ + i3++ + i4++ : 4 8 13 19 40

        construct 3
        call i++ for 3
        call i++ for 4
        call i++ for 5
        call i++ for 6
        call + for 6 and 5
        call + for 11 and 4
        call + for 15 and 3
        i++ + i++ + i++ + i++ : 7 18

        x 7 xx 12

with the contrast of the results from test case one and two using Int type i defined, i predicted that the test case three should print x 7 xx 18, but it didn't.

my question is how to explain the result?

terry
  • 341
  • 2
  • 6
  • 13
  • 3
    This is undefined behavior. Don't look for any logic here there won't be. – Borgleader Jul 30 '13 at 03:34
  • 1
    Please post code as formatted text, not as an image, so that answerers can copy it to their own environments to play with. – Barmar Jul 30 '13 at 04:06

2 Answers2

2

A sequence point defines any point in a computer program's execution at which it is guaranteed that all side effects of previous evaluations will have been performed, and no side effects from subsequent evaluations have yet been performed. They are often mentioned in reference to C and C++, because the result of some expressions can depend on the order of evaluation of their subexpressions.

Here there are two sequence points at i++(first) and i++(second one). And the Standard says:

" Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression."

So if you try to modify values of a variable between two sequence points, then it will give undefined behavior.

Wiki Link for Sequence Points http://en.wikipedia.org/wiki/Sequence_point

Saby
  • 718
  • 9
  • 29
0

An expression of the form i++ + i++ will have a compiler-dependent result. The evaluation order is not well defined by the standard, hence, we call this undefined behavior.

user123
  • 8,970
  • 2
  • 31
  • 52