Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++ and C# are multiple condition checks performed in a predetermined or random sequence?

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?

like image 449
User Avatar asked May 07 '09 21:05

User


People also ask

WHAT IS &N in C?

&n writes the address of n . The address of a variable points to the value of that variable.

What is #if in C?

Description. In the C Programming Language, the #if directive allows for conditional compilation. The preprocessor evaluates an expression provided with the #if directive to determine if the subsequent code should be included in the compilation process.

IS & the same as * in C?

* can be either the dereference operator or part of the pointer declaration syntax. & can be either the address-of operator or (in C++) part of the reference declaration syntax.


2 Answers

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.

like image 94
Robert Paulson Avatar answered Sep 21 '22 04:09

Robert Paulson


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#.

like image 39
RichieHindle Avatar answered Sep 22 '22 04:09

RichieHindle