Why is the behavior of `x -> 0` not undefined, and` x = x - `is this?

As you know, this goes through zero:

while (x-- > 0) { /* also known as x --> 0 */
  printf("x = %d\n", x);
}

But x = x--gives undefined behavior .


Both examples need some “return” to a value x--that I don’t think. How can it be that is x-- > 0determined, but is x = x--not?

+3
source share
5 answers

Because in x = x--you change the value twice xwithout an intermediate point in the sequence. Thus, the order of operations is not defined. The x-- > 0value xchanges once, and it is clearly defined that the result of the evaluation x--will be the value xbefore decrement.

+19

, "" x--, ". -, , . -, , , undefined x = x--.

x = x-- undefined, x . "" " ".

x = x-- , , undefined undefined . . postfix --. x . undefined de jure.

, x 5, x 4 ( ) 5 ( ) . , x 4 5 .

(, 4 vs 5) UB. , , , undefined, , .

+7

, . . : http://en.wikipedia.org/wiki/Sequence_point

= , , x , x.

while x-- > 0, x--, , undefined, x .

+3

- , .

+2

fooobar.com/questions/2129/.... , = , , , :

load i to reg
increment i
assign reg to i
=> i has previous value of i

load i to reg
assign reg to i
increment i
=> i has value of previous value of i + 1

In general: avoid assigning (this includes modifying pre / post ++ / -) to the same variable twice in the same expression.

+1
source

All Articles