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

Situation: checking state in C ++ or C # with many criteria:

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

I have always believed that the sequence in which these checks are performed is not guaranteed. Therefore, this is not necessarily the first condition1, then condition 2, and only then condition 3. I found out in my time with C ++. I think they told me that I read it somewhere.

Until I know that I always wrote safe code to account for possible zero-point pointers in the following situation:

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

So I wrote:

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

Since I was not sure that the non-null check would be executed first, and only then would the instance method be called to perform the second check.

Now our greatest community minds are telling me that the sequence in which these checks are performed will be performed from left to right.

I am very surprised. Is this really true for C ++ and C #?

Has anyone else heard the version I heard before?

+7
c ++ c # non-deterministic deterministic
source share
4 answers

Short answer from left to right with a short circuit rating. 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 a state before branching (e.g. VB6).

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

Reference: MSDN C # Operators and their order or priority.

+14
source share

They are defined to evaluate from left to right, and to stop evaluating when one of them evaluates to false. This is true for both C ++ and C #.

+2
source share

I do not think that there is or was another way. It would be like the compiler decided to run statements unconditionally. :) Now, some languages ​​(for example, VB.NET) have different logical operators for a short circuit rather than a short circuit. But the order is always well defined at compile time.

Here is the operator priority from the C # language specification. From the specification ...

With the exception of assignment operators, all binary operators are left-associative, which means that operations are performed from left to right correctly. For example, x + y + z is evaluated as (x + y) + z.

0
source share

They must be executed from left to right. This allows you to work with short circuit assessment.

See the Wikipedia article for more details.

0
source share

All Articles