开发者

Undefined behaviour of sub-expressions

Does this result in undefined behaviour because the order of evaluation will be unspecified?

int i =开发者_Python百科 0, j = 0, k = 0;
int result = i++ + ++j + k++;


No, the result of the evaluation doesn't depend on the unspecified order of evaluation of the sub-expressions.

Undefined behavior only occurs in this situation if two side effects that affect the same object are unsequenced relative to each other or a side effect and a value computation of the same object are unsequenced. The side-effect and value computation of both prefix and postfix increment are explicitly sequenced.


The order of evaluation is unspecified, but who cares? Each operand acts on a completely distinct object. Nothing undefined here.


No, the behavior is perfectly well-defined: j is incremented, then addition is performed, then i and k are incremented. The only thing that is unspecified is the order in which the increments on i and k are performed. The postcondition is i==1, j==1, k==1, result==1.


The rule is that the results are unspecified if you modify a variable more than once. You haven't done that in your example.


It's fine here because you don't use the same variable twice.

What you have is equivalent to:

int i = 0, j = 0, k = 0;
++j;
int result = i + j + k;
++i;
++k;

If you were to have instead int result = i++ + ++i + i++; then you'd have a problem because the order of the increments is unspecified, and you depend on that order.


Here result will be always 1. The values of j, k, and i will be all 1. Also, note that separator for several variable declaration is ,, and not ;:

int i=0, j=0, k=0;


No, it's a classic/well known c++ sequence point issue, see link here for much more detail http://en.wikipedia.org/wiki/Sequence_point


Here:

int result = i++ + ++j + k++;

Is Equivalent too:

<SP>
(a1)int t1 = i;     // i++ part one: The result of post-increment is the original value
(a2)     i = i + 1; // i++ part two: the increment part separated from the result
(b1)     j = j + 1;
(b2)int t2 = j;     // The result of pre-increment is the new value
(c1)int t3 = k;     // k++ part one: The result of post-increment is the original value
(c2)     k = k + 1;
(d) int t4 = t1 + t2;
(e) int t5 = t3 + t4;    
(f) int result = t5;
<SP>

The constraints are:

(a1) is before (a2)
(a1) is before (d)
(b1) is before (b2)
(b2) is before (d) 
(c1) is before (c2)
(c1) is before (e)
(d)  is before (e)
(e)  is before (f)

As long as the above constraints are maintained the instructions can be re-ordered as much as the compiler likes. But the constraints guarantee that the result is well formed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜