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"?

-------------Problems Reply------------

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

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

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!

vb.net

if( x isNot Nothing AndAlso x.go()) then

  1. Evaluation is done left to right
  2. AndAlso operator makes sure that only if the left side was TRUE, the right side will be evaluated (very important, since ifx is nothing x.go will crash)

You may use And instead ofAndAlso in vb. in which case the left side gets evaluated first as well, but the right side will get evaluated regardless of result.

Best Practice: Always use AndAlso, unless you have a very good reason why not to.



It was asked in a followup why or when would anyone use And instead of AndAlso (or & instead of &&): Here is an example:

if ( x.init() And y.init()) then
x.process(y)
end
y.doDance()

In this case, I want to init both X and Y. Y must be initialized in order for y.DoDance to be able to execute. However, in the init() function I am doing also some extra thing like checking a socket is open, and only if that works out ok, for both, I should go ahead and do the x.process(y).

Again, this is probably not needed and not elegant in 99% of the cases, that is why I said that the default should be to use AndAlso.

@shsteimer

The concept modesty is referring to is operator overloading. in the statement: ... A is evaluated first, if it evaluates to false, B is never evaluated. The same applies to

That's not operator overloading. Operator overloading is the term given for letting you define custom behaviour for operators, such as *, +, = and so on.

This would let you write your own 'Log' class, and then do

a = new Log(); // Log class overloads the + operator
a + "some string"; // Call the overloaded method - otherwise this wouldn't work because you can't normally add strings to objects.

Doing this

a() || b() // be never runs if a is true

is actually called Short Circuit Evaluation

ZombieSheep is dead-on. The only "gotcha" that might be waiting is that this is only true if you are using the && operator. When using the & operator, both expressions will be evaluated every time, regardless if one or both evaluate to false.

if (amHungry & whiteCastleIsNearby)
{
// The code will check if White Castle is nearby
// even when I am not hungry
}

if (amHungry && whiteCastleIsNearby)
{
// The code will only check if White Castle is nearby
// when I am hungry
}

Note that there is a difference between && and & regarding how much of your expression is evaluated.

&& is known as a short-circuited boolean AND, and will, as noted by others here, stop early if the result can be determined before all the sub-expressions are evaluated.

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

As such:

if (a() && b())

Will only call b if a returns true.

however, this:

if (a() & b())

Will always call both a and b, even though the result of calling a is false and thus known to be false regardless of the result of calling b.

This same difference exists for the || and | operators.

Some languages have interesting situations where expressions are executed in a different order. I am specifically thinking of Ruby, but I'm sure they borrowed it from elsewhere (probably Perl).

The expressions in the logic will stay left to right, but for example:

puts message unless message.nil?

The above will evaluate "message.nil?" first, then if it evaluates to false (unless is like if except it executes when the condition is false instead of true), "puts message" will execute, which prints the contents of the message variable to the screen.

It's kind of an interesting way to structure your code sometimes... I personally like to use it for very short 1 liners like the above.

Edit:

To make it a little clearer, the above is the same as:

unless message.nil?
puts message
end

The left one, then stops if it is null.

Edit: In vb.net it will evaluate both and possibly throw an error, unless you use AndAlso

The concept modesty is referring to is operator overloading. in the statement:

if( A && B){
// do something
}

A is evaluated first, if it evaluates to false, B is never evaluated. The same applies to

if(A || B){
//do something
}

A is evaluated first, if it evaluates to true, B is never evaluated.

This concept, overloading, applies to (i think) all of the C style languages, and many others as well.

Nopes, at least the C# compiler doesn't work backwards (in either && or ||). It's left to right.

When things are all in-line, they're executed left-to-right.

When things are nested, they're executed inner-to-outer. This may seem confusing as usually what's "innermost" is on the right-hand side of the line, so it seems like it's going backwards...

For example

a = Foo( 5, GetSummary( "Orion", GetAddress("Orion") ) );

Things happen like this:

  • Call GetAddress with the literal "Orion"
  • Call GetSummary with the literal "Orion" and the result of GetAddress
  • Call Foo with the literal 5 and the result of GetSummary
  • Assign this value to a

I like Orion's responses. I'll add two things:

  1. The left-to-right still applies first
  2. The inner-to-outer to ensure that all arguments are resolved before calling the function

Say we have the following example:

a = Foo(5, GetSummary("Orion", GetAddress("Orion")),
GetSummary("Chris", GetAddress("Chris")));

Here's the order of execution:

  1. GetAddress("Orion")
  2. GetSummary("Orion", ...)
  3. GetAddress("Chris")
  4. GetSummary("Chris", ...)
  5. Foo(...)
  6. Assigns to a

I can't speak about C#'s legal requirements (although I did test a similar example using Mono before writing this post), but this order is guaranteed in Java.

And just for completeness (since this is a language-agnostic thread as well), there are languages like C and C++, where the order is not guaranteed unless there is a sequence point. References: 1, 2. In answering the thread's question, however, && and || are sequence points in C++ (unless overloaded; also see OJ's excellent answer). So some examples:

  • foo() && bar()
  • foo() & bar()

In the && case, foo() is guaranteed to run before bar() (if the latter is run at all), since && is a sequence point. In the & case, no such guarantee is made (in C and C++), and indeed bar() can run before foo(), or vice versa.

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

Suppose you have flags, say for file attributes. Suppose you've defined READ as 4, WRITE as 2, and EXEC as 1. In binary, that's:

READ 0100
WRITE 0010
EXEC 0001

Each flag has one bit set, and each one is unique. The bitwise operators let you combine these flags:

flags = READ & EXEC; // value of flags is 0101

I have heard somewhere that compilers work backwards, but I am unsure how true this is.

You use & when you specifically want to evaluate all the sub-expressions, most likely because they have side-effects you want, even though the final result will be false and thus not execute your then part of your if-statement.

Note that & and | operates for both bitwise masks and boolean values and is not just for bitwise operations. They're called bitwise, but they are defined for both integers and boolean data types in C#.

@csmba:

It was asked in a followup why or when would anyone use And instead of AndAlso (or & instead of &&): Here is an example:

if ( x.init() And y.init()) then
x.process(y)
end
y.doDance()

In this case, I want to init both X and Y. Y must be initialized in order for y.DoDance to be able to execute. However, in the init() function I am doing also some extra thing like checking a socket is open, and only if that works out ok, for both, I should go ahead and do the x.process(y).

I believe this is rather confusing. Although your example works, it's not the typical case for using And (and I would probably write this differently to make it clearer). And (& in most other languages) is actually the bitwise-and operation. You would use it to calculate bit operations, for example deleting a flag bit or masking and testing flags:

Dim x As Formatting = Formatting.Bold Or Formatting.Italic
If (x And Formatting.Italic) = Formatting.Italic Then
MsgBox("The text will be set in italic.")
End If

The D programming language Does do left-to-right evaluation with short circuiting and doesn't allow overloading of the && and '||' operators.

Category:c# Views:3 Time:2008-08-07

Related post

  • How is the order of Compilation of source files decided 2009-04-01

    I have a workspace containing many *.c files, which I compile. (I could use any toolchain say MSVC6.0, or gcc etc) Which source file is compiled first? How is the order of the files to be compiled subsequently decided? --------------Solutions--------

  • How to represent different types of documents in a logical order 2011-06-16

    I need to represent different types of documents in a logical order. So I have a list of objects with IDs. I need to make a comparer which orders these objects by a "manual" rule. Order by id must be 2,32,5,12,8,43... and so on. I use LINQ documents.

  • Strange C# compiler behavior (overload resolution) 2011-11-22

    I've found very strange C# compiler behavior for following code: var p1 = new SqlParameter("@p", Convert.ToInt32(1)); var p2 = new SqlParameter("@p", 1); Assert.AreEqual(p1.Value, p2.Value); // PASS var x = 0; p1 = new SqlParameter("@p", Convert.ToIn

  • Logical order of Story XML in IDML 2011-12-01

    I am new to IDML and I am trying to understand this. I have figured out that IDML is zip file containing multiple XML files. I have opened the designmap.xml and saw the StoryLine attribute in Document element. However, this order in the StoryLine atr

  • what is order of compiling a class in java 2011-12-03

    what is order of compiling a java class in JVM as below example import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class FindoutDtDiff { /** * @param args */ public static vo

  • C# Compiler Behavior Question? 2009-10-12

    Hey everyone, in the following code, what should the result of d be after the second expression? int d = 1; d += d++; One would assume d is 3 afterwards but the unary increment d++ doesn't seem to take effect and d retains a value of 2. Is there a na

  • Determine static initialization order after compilation? 2009-08-03

    In C++, I know that the compiler can choose to initialize static objects in any order that it chooses (subject to a few constraints), and that in general you cannot choose or determine the static initialization order. However, once a program has been

  • If I registered a TLB do I still need to register the ocx in order to compile? 2009-11-19

    I am trying to compile a vb6 application and I can't register the ocx files. In order to attempt to compile I have replaced the Object= lines in the .vbp file with Reference= lines to the TLB instead of the OCX. Now when I compile I get the following

  • Strange compiler behavior with float literals vs float variables 2010-06-21

    I have noticed an interesting behavior with float rounding / truncation by the C# compiler. Namely, when a float literal is beyond the guaranteed representable range (7 decimal digits), then a) explicitly casting a float result to float (a semantical

  • Strange (possibly wrong?) C# compiler behavior with method overloading and enums 2010-06-30

    today I discovered a very strange behavior with C# function overloading. The problem occurs when I have a method with 2 overloads, one accepting Object and the other accepting Enum of any type. When I pass 0 as parameter, the Enum version of the meth

  • How does Visual Studio determine the order to compile IDL files? 2010-07-13

    I have a COM project that contains a number of IDL files, some of which are imported into other ones. How does Visual Studio decide which ones to compile (using MIDL) first? I want to control the order. I have a master IDL file which contains my libr

  • Why does a struct consisting of a char, short, and char (in that order), when compiled in C++ with 4-byte packing enabled, come to a 6-byte struct? 2010-09-03

    I thought I understood how C/C++ handled struct member alignment. But I'm getting strange results for a particular arrangement in Visual Studio 2008 and 2010. Specifically, I'm finding that a struct consisting of a char, short, and char is compiled i

  • How should I use g++'s -finput-charset compiler option correctly in order to compile a non-UTF-8 source file? 2012-04-27

    I'm trying to compile a UTF-16BE C++ source file in g++ with -finput-charset compiler option but I'm always getting a bunch of errors. More details follow. My environment(in CentOS Linux): g++: 4.1.2 iconv: 2.5 Linux language(in Terminal): LANG="en_U

  • Strange Compiler Behavior Regarding Default Constructors in C++ 2010-01-16

    class TestClass { public: TestClass(int i) { i = i; }; private: int i; } class TestClass2 { private: TestClass testClass; } Why does the above code compile fine even when we have not provided a default constructor? Only if someone instantiates TestCl

  • Tricky compiler behavior 2010-03-23

    Simple java code snippet. It has three classes. After compiling the code please delete A.class and then execute the code. Code still runs, why its not checking whether the byte code of A exists or not? class A { static { System.out.println("In the cl

  • Any difference in compiler behavior for each of these snippets? 2010-04-09

    Please consider following code: 1. uint16 a = 0x0001; if(a < 0x0002) { // do something } 2. uint16 a = 0x0001; if(a < uint16(0x0002)) { // do something } 3. uint16 a = 0x0001; if(a < static_cast<uint16>(0x0002)) { // do something } 4.

  • About the internal logic of C compiler 2010-07-15

    When we build a programe,some symbols are to be resolved at link time(like those in a .lib), but some can be resolved at run time(those in a .dll), my doubt is that how does the compiler know about this, or how do we notify the compiler about this? -

  • Netbeans & Maven: different compilation behavior 2010-08-11

    I am using Netbeans and Maven projects. In some case Netbeans show me compilation failures (red ballon) BUT Maven compile everything without any problem! What can be the reason of this difference. I already checked that both are using the same JDK ve

  • Mac server in order to compile obj-c projects? 2010-09-18

    Is it possible to write an obj-C code with any text editor and then upload it to Mac server to compile it using Xcode?? I know that it is possible to compile your project using Xcode without open it something like use some command lines, but I am not

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.086 (s). 11 q(s)