开发者

is this c code still not of a defined output?

I was 开发者_如何学Creading C Traps and Pitfalls and read that the following code may work on some implementations and won't on others due to an undefined order of = and ++. Is this still true of C?

int i = 0;
while (i < n)
    y[i] = x[i++];

If so, that's really incredible.


Nothing incredible. Pretty defined undefined behavior. Read more about sequence points. Just writing as:

int i = 0;
while (i < n)
{
    y[i] = x[i];
    i++;
}

is safer and more readable.


The postfix ++ has a result and a side effect. The result is the current value of the operand. The side effect is that the operand gets incremented by one. Where the problem comes in is that the side effect doesn't have to be applied immediately after the expression has been evaluated; it only has to be applied before the next sequence point.

From the C language standard (n1256):

6.5 Expressions
...
2 Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression.72) Furthermore, the prior value shall be read only to determine the value to be stored.73)
...
72) A floating-point status flag is not an object and can be set more than once within an expression.

73) This paragraph renders undefined statement expressions such as

    i = ++i + 1;
    a[i++] = i;
while allowing

    i = i + 1;
    a[i] = i;


It is not particularly suprising that this code has undefined behaviour, because it's semantically ambiguous: In y[i], which value of i is intended? The value before the increment, or after? (Bear in mind that the = operator does not specify that one side is evaluated before the other)


Yes, it's still UB.

§ 1.9p7 At certain specified points in the execution sequence called sequence points, all side effects of previous evaluations shall be complete and no side effects of subsequent evaluations shall have taken place. (§1.9/7)


Well, i++ means "increment i after using its value", so it I think it's correct (well, I changed idea reading the other posts). Rather I would do:

while((i++) < n)
    y[i] = x[i];
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜