So, if I have an expression like:
if (obj != null && i++ % divisor == 0)
{
....
}
and obj is null, then i is never incremented. If I use
i++;
if (obj != null && i % divisor == 0)
{
....
}
instead, then, of course, i is incremented.
Is this by design? I understand short-circuit evaluation from an optimization point of view, but I had (incorrectly) assumed that the compiler would recognize the post-increment expression and evaluate it regardless.
(If this is in the spec, I couldn't find it - just looking for some (gasp) opinions here.)
Update
Here's the actual code.
private int _frameNumber = 0;
private void simulator_OnFrameEnd(object sender, System.EventArgs e)
{
_frameNumber++;
if (_visualizer != null && _frameNumber % _config.VisualizerUpdateFrequency == 0)
{
var field = _simulator.GetField(_config.PreviewField);
_visualizer.Update(field, _simulator.FrameTime);
}
if (_frameNumber % _config.OptimizerRegridFrequency == 0)
{
_simulator.UpdateFieldGrids();
}
}
It is most definitely by design. MSDN states:
The operation
x && ycorresponds to the operationx & yexcept that if x is false, y is not evaluated, because the result of the AND operation is false no matter what the value of y is. This is known as "short-circuit" evaluation.
So, it doesn't matter what your statement is, whether it has a post-increment or not, it won't be evaluated if it's short-circuited.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With