I saw this code today :
if(++counter == 10)
{
//Do Something
foo();
}
I think this is bad style, but, is the execution compiler dependent aswell? say the counter is set to 8 before we get to this line, it’s going to increment it, then compare 10 to 8, the value before, or compare 10 to 9, the value of counter after it got incremented?
What do you think SO? Is this common practice? bad style?
There’s nothing compiler-dependent in the behavior of this code (besides possible overflow behavior). Whether it is a good style is a matter of personal preference. I generally avoid making modifications in conditionals, but sometimes it can be useful and even elegant.
This code is guaranteed to compare the new value to 10 (i.e. 9 is compared to 10 in your example). Formally, it is incorrect to say that the comparison takes place after
countergets incremented. There’s no “before” or “after” here. The new value can get pre-calculated and compared to 10 even before it is physically placed intocounter.In other words, the evaluation of
++counter == 10can proceed asor as
Note that in the first case
counteris incremented before the comparison, while in the second case it is incremented after the comparison. Both scenarios are valid and perfectly possible in practice. Both scenarios produce the same result required by the language specification.