Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# logic order and compiler behavior

In C#, (and feel free to answer for other languages), what order does the runtime evaluate a logic statement?

Example:

DataTable myDt = new DataTable();
if (myDt != null && myDt.Rows.Count > 0)
{
    //do some stuff with myDt
}

Which statement does the runtime evaluate first -

myDt != null

or:

myDt.Rows.Count > 0

?

Is there a time when the compiler would ever evaluate the statement backwards? Perhaps when an "OR" operator is involved?


& is known as a logical bitwise operator and will always evaluate all the sub-expressions

What is a good example of when to use the bitwise operator instead of the "short-circuited boolean"?

like image 950
Seibar Avatar asked Aug 07 '08 20:08

Seibar


3 Answers

C# : Left to right, and processing stops if a non-match (evaluates to false) is found.

like image 60
ZombieSheep Avatar answered Oct 11 '22 11:10

ZombieSheep


"C# : Left to right, and processing stops if a match (evaluates to true) is found."

Zombie sheep is wrong, not enough rep to down vote it.

The question is about the && operator, not the || operator.

In the case of && evaluation will stop if a FALSE is found.

In the case of || evaluation stops if a TRUE is found.

like image 37
Brian Leahy Avatar answered Oct 11 '22 12:10

Brian Leahy


I realise this question has already been answered, but I'd like to throw in another bit of information which is related to the topic.

In languages, like C++, where you can actually overload the behaviour of the && and || operators, it is highly recommended that you do not do this. This is because when you overload this behaviour, you end up forcing the evaluation of both sides of the operation. This does two things:

  1. It breaks the lazy evaluation mechanism because the overload is a function which has to be invoked, and hence both parameters are evaluated before calling the function.
  2. The order of evaluation of said parameters isn't guaranteed and can be compiler specific. Hence the objects wouldn't behave in the same manner as they do in the examples listed in the question/previous answers.

For more info, have a read of Scott Meyers' book, More Effective C++. Cheers!

like image 32
OJ. Avatar answered Oct 11 '22 11:10

OJ.