Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"x = ++x" is it really undefined?

I am using Coverity Prevent on a project to find errors.

It reports an error for this expression (The variable names are of course changed):

x=
   (a>= b) ?
   ++x: 0;

The message is:

EVALUATION_ORDER defect: In "x=(a>= b) ? ++x: 0;", "x" is written in "x" (the assignment LHS) and written in "(a>= b) ? ++x: 0;" but the order in which the side effects take place is undefined because there is no intervening sequence point. END OF MESSAGE

While I can understand that "x = x++" is undefined, this one is a bit harder for me. Is this one a false positive or not?

like image 529
Magnus Andermo Avatar asked Sep 01 '10 14:09

Magnus Andermo


1 Answers

Conditional operator ?: has a sequence point between evaluation of the condition (first operand) and evaluation of second or third operand, but it has no dedicated sequence point after the evaluation of second or third operand. Which means that two modifications of x in this example are potentially conflicting (not separated by a sequence point). So, Coverity Prevent is right.

Your statement in that regard is virtually equivalent to

a >= b ? x = ++x : x = 0;

with the same problem as in x = ++x.

Now, the title of your question seems to suggest that you don't know whether x = ++x is undefined. It is indeed undefined. It is undefined for the very same reason x = x++ is undefined. In short, if the same object is modified more than once between a pair of adjacent sequence points, the behavior is undefined. In this case x is modified by assignment and by ++ an there's no sequence point to "isolate" these modifications from each other. So, the behavior is undefined. There's absolutely no difference between ++x and x++ in this regard.

like image 56
AnT Avatar answered Sep 23 '22 01:09

AnT