Monday, 27 February 2012

I got an interesting issue with Coverity Static Analysis. There is code that looks like

foo = (foo == bar ? foo : ++foo)

CSA complained that there is an order evaluation violation. First I thought this was due to the fact that foo is in fact a class variable so the pre-increment would actually look like ++this->foo, but this is not a problem because the -> operator is evaluated before the pre-increment.

On discussion with Coverity they think that when the false branch holds true this would evaluate tofoo = foo = foo +1

But I think this is not true because the tertiary operator is a sequence point. More precisely the ? is. I think this might be due to the fact that K&R wanted the tertiary operator to work exactly like an if-then-else expression. Thus the correct way of looking at the expression would be to think of it as this:

if (foo == bar)
foo = foo;
else
++foo;

Stupid code (not mine!) but there is no bug.

The key to this is to understand that the tertiary operator has a sequence point unlike the assignment operator!