Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pre/post-increment in conditional skipped by short-circuit evaluation

Tags:

c#

compilation

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();

        }

    }
like image 912
3Dave Avatar asked Nov 19 '25 18:11

3Dave


1 Answers

It is most definitely by design. MSDN states:

The operation x && y corresponds to the operation x & y except 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.

like image 148
FishBasketGordo Avatar answered Nov 22 '25 07:11

FishBasketGordo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!