views:

981

answers:

4

Situation: condition check in C++ or C# with many criteria:

if (condition1 && condition2 && condition3)
{
    // Do something
}

I've always believed the sequence in which these checks are performed is not guaranteed. So it is not necessarily first condition1 then condition2 and only then condition3. I learned it in my times with C++. I think I was told that or read it somewhere.

Up until know I've always written secure code to account for possible null pointers in the following situation:

if ((object != null) && (object.SomeFunc() != value))
{
    // A bad way of checking (or so I thought)
}

So I was writing:

if (object != null)
{
    if (object.SomeFunc() != value)
    {
        // A much better and safer way
    }
}

Because I was not sure the not-null check will run first and only then the instance method will be called to perform the second check.

Now our greatest community minds are telling me the sequence in which these checks are performed is guaranteed to run in the left-to-right order.

I'm very surprised. Is it really so for both C++ and C# languages?

Has anybody else heard the version I heard before now?

+12  A: 

Short Answer is left to right with short-circuit evaluation. The order is predictable.

// perfectly legal and quite a standard way to express in C++/C#
if( x != null && x.Count > 0 ) ...

Some languages evaluate everything in the condition before branching (VB6 for example).

// will fail in VB6 if x is Nothing. 
If x Is Not Nothing And x.Count > 0 Then ...

Ref: MSDN C# Operators and their order or precedence.

Robert Paulson
RichieHindle
@RichieHindle - yes, my recollection of VB6/VBScript is thankfully very old. I'll update
Robert Paulson
A: 

They are defined to be evaluated from left-to-right, and to stop evaluating when one of them evaluates to false. That's true in both C++ and C#.

RichieHindle
A: 

I don't think there is or has been any other way. That would be like the compiler deciding to run statements out of order for no reason. :) Now, some languages (like VB.NET) have different logical operators for short-circuiting and not short-circuiting. But, the order is always well defined at compile time.

Here is the operator precedence from the C# language spec. From the spec ...

Except for the assignment operators, all binary operators are left-associative, meaning that operations are performed from left to right. For example, x + y + z is evaluated as (x + y) + z.

JP Alioto
Again, precedence, associativity and order of subexpression evaluation are three different things. You cannot determine order from precedence in C#.
Eric Lippert
Also, I regret that the specification is poorly worded in the bit that you quoted. I've been trying to get that fixed.
Eric Lippert
JP Alioto
A: 

They have to be performed from left to right. This allows short circuit evaluation to work.

See the Wikipedia article for more information.

Soo Wei Tan