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

<p>Example:</p>

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

<p>Which statement does the runtime evaluate first - </p>

<pre><code>myDt != null
</code></pre>

<p>or:</p>

<pre><code>myDt.Rows.Count &gt; 0
</code></pre>

<p>?</p>

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

<hr>

<blockquote>
  <p>&amp; is known as a logical bitwise operator and will always evaluate all the sub-expressions</p>
</blockquote>

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

[{'answer_id': 5272, 'author': 'Shawn', 'author_id': 26, 'author_profile': 'https://Stackoverflow.com/users/26', 'pm_score': 2, 'selected': False, 'text': '<p>The left one, then stops if it is null.</p>\n\n<p>Edit: In vb.net it will evaluate both and possibly throw an error, unless you use AndAlso</p>\n'}, {'answer_id': 5276, 'author': 'ZombieSheep', 'author_id': 377, 'author_profile': 'https://Stackoverflow.com/users/377', 'pm_score': 5, 'selected': True, 'text': '<p>C# : Left to right, and processing stops if a non-match (evaluates to false) is found.</p>\n'}, {'answer_id': 5277, 'author': 'GateKiller', 'author_id': 383, 'author_profile': 'https://Stackoverflow.com/users/383', 'pm_score': 0, 'selected': False, 'text': '<p>I have heard somewhere that compilers work backwards, but I am unsure how true this is.</p>\n'}, {'answer_id': 5278, 'author': 'csmba', 'author_id': 350, 'author_profile': 'https://Stackoverflow.com/users/350', 'pm_score': 3, 'selected': False, 'text': '<p><strong>vb.net</strong></p>\n\n<pre><code>if( x isNot Nothing AndAlso x.go()) then\n</code></pre>\n\n<ol>\n<li>Evaluation is done left to right</li>\n<li><strong>AndAlso</strong> 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)</li>\n</ol>\n\n<p>You may use <strong>And</strong> 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. </p>\n\n<p>Best Practice: Always use AndAlso, unless you have a very good reason why not to.</p>\n\n<hr>\n\n<p><strong>It was asked in a followup why or when would anyone use And instead of AndAlso (or &amp; instead of &amp;&amp;):</strong>\nHere is an example:</p>\n\n<pre><code>if ( x.init() And y.init()) then\n   x.process(y)\nend \ny.doDance()\n</code></pre>\n\n<p>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 <strong>both</strong>, I should go ahead and do the x.process(y).</p>\n\n<p>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 <em>AndAlso</em>.</p>\n'}, {'answer_id': 5279, 'author': 'shsteimer', 'author_id': 292, 'author_profile': 'https://Stackoverflow.com/users/292', 'pm_score': 2, 'selected': False, 'text': '<p>The concept modesty is referring to is operator overloading.  in the statement:</p>\n\n<pre><code>if( A &amp;&amp; B){\n    // do something\n}\n</code></pre>\n\n<p>A is evaluated first, if it evaluates to false, B is never evaluated.  The same applies to</p>\n\n<pre><code>if(A || B){\n    //do something\n}\n</code></pre>\n\n<p>A is evaluated first, if it evaluates to true, B is never evaluated.</p>\n\n<p>This concept, overloading, applies to (i think) all of the C style languages, and many others as well.</p>\n'}, {'answer_id': 5292, 'author': 'Brad Tutterow', 'author_id': 308, 'author_profile': 'https://Stackoverflow.com/users/308', 'pm_score': 2, 'selected': False, 'text': '<p>ZombieSheep is dead-on.  The only "gotcha" that might be waiting is that this is only true if you are using the &amp;&amp; operator.  When using the &amp; operator, both expressions will be evaluated every time, regardless if one or both evaluate to false.</p>\n\n<pre><code>if (amHungry &amp; whiteCastleIsNearby)\n{\n   // The code will check if White Castle is nearby\n   // even when I am not hungry\n}\n\nif (amHungry &amp;&amp; whiteCastleIsNearby)\n{\n   // The code will only check if White Castle is nearby\n   // when I am hungry\n}\n</code></pre>\n'}, {'answer_id': 5295, 'author': 'Lasse V. Karlsen', 'author_id': 267, 'author_profile': 'https://Stackoverflow.com/users/267', 'pm_score': 2, 'selected': False, 'text': '<p>Note that there is a difference between &amp;&amp; and &amp; regarding how much of your expression is evaluated.</p>\n\n<p>&amp;&amp; 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.</p>\n\n<p>&amp; is known as a logical bitwise operator and will always evaluate all the sub-expressions.</p>\n\n<p>As such:</p>\n\n<pre><code>if (a() &amp;&amp; b())\n</code></pre>\n\n<p>Will only call <em>b</em> if <em>a</em> returns <em>true</em>.</p>\n\n<p>however, this:</p>\n\n<pre><code>if (a() &amp; b())\n</code></pre>\n\n<p>Will always call both <em>a</em> and <em>b</em>, even though the result of calling <em>a</em> is false and thus known to be <em>false</em> regardless of the result of calling <em>b</em>.</p>\n\n<p>This same difference exists for the || and | operators.</p>\n'}, {'answer_id': 5301, 'author': 'Mike Stone', 'author_id': 122, 'author_profile': 'https://Stackoverflow.com/users/122', 'pm_score': 2, 'selected': False, 'text': '<p>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).</p>\n\n<p>The expressions in the logic will stay left to right, but for example:</p>\n\n<pre><code>puts message unless message.nil?\n</code></pre>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<p>Edit:</p>\n\n<p>To make it a little clearer, the above is the same as:</p>\n\n<pre><code>unless message.nil?\n  puts message\nend\n</code></pre>\n'}, {'answer_id': 5308, 'author': 'Vaibhav', 'author_id': 380, 'author_profile': 'https://Stackoverflow.com/users/380', 'pm_score': 1, 'selected': False, 'text': "<p>Nopes, at least the C# compiler doesn't work backwards (in either &amp;&amp; or ||). It's left to right.</p>\n"}, {'answer_id': 5372, 'author': 'Bruce Alderman', 'author_id': 311, 'author_profile': 'https://Stackoverflow.com/users/311', 'pm_score': 1, 'selected': False, 'text': '<blockquote>\n  <p>What is a good example of when to use the bitwise operator instead of the "short-circuited boolean"?</p>\n</blockquote>\n\n<p>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:</p>\n\n<pre><code>READ  0100  \nWRITE 0010  \nEXEC  0001\n</code></pre>\n\n<p>Each flag has one bit set, and each one is unique. The bitwise operators let you combine these flags:</p>\n\n<pre><code>flags = READ &amp; EXEC; // value of flags is 0101\n</code></pre>\n'}, {'answer_id': 5378, 'author': 'Orion Edwards', 'author_id': 234, 'author_profile': 'https://Stackoverflow.com/users/234', 'pm_score': 3, 'selected': False, 'text': '<p>@shsteimer </p>\n\n<blockquote>\n  <p>The concept modesty is referring to is operator overloading. in the statement:\n  ...\n  A is evaluated first, if it evaluates to false, B is never evaluated. The same applies to</p>\n</blockquote>\n\n<p>That\'s not operator overloading. Operator overloading is the term given for letting you define custom behaviour for operators, such as *, +, = and so on.</p>\n\n<p>This would let you write your own \'Log\' class, and then do </p>\n\n<pre><code>a = new Log(); // Log class overloads the + operator\na + "some string"; // Call the overloaded method - otherwise this wouldn\'t work because you can\'t normally add strings to objects.\n</code></pre>\n\n<p>Doing this</p>\n\n<pre><code>a() || b() // be never runs if a is true\n</code></pre>\n\n<p>is actually called <a href="http://en.wikipedia.org/wiki/Short-circuit_evaluation" rel="noreferrer">Short Circuit Evaluation</a></p>\n'}, {'answer_id': 5382, 'author': 'Lasse V. Karlsen', 'author_id': 267, 'author_profile': 'https://Stackoverflow.com/users/267', 'pm_score': 0, 'selected': False, 'text': "<p>You use &amp; 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 <em>false</em> and thus not execute your <em>then</em> part of your <em>if</em>-statement.</p>\n\n<p>Note that &amp; and | operates for both bitwise masks and boolean values and is not just for bitwise operations. They're <em>called</em> bitwise, but they are defined for both integers and boolean data types in C#.</p>\n"}, {'answer_id': 5384, 'author': 'Orion Edwards', 'author_id': 234, 'author_profile': 'https://Stackoverflow.com/users/234', 'pm_score': 1, 'selected': False, 'text': '<p>When things are all in-line, they\'re executed left-to-right.</p>\n\n<p>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...</p>\n\n<p>For example</p>\n\n<pre><code>a = Foo( 5, GetSummary( "Orion", GetAddress("Orion") ) );\n</code></pre>\n\n<p>Things happen like this:</p>\n\n<ul>\n<li>Call <code>GetAddress</code> with the literal <code>"Orion"</code></li>\n<li>Call <code>GetSummary</code> with the literal <code>"Orion"</code> and the result of <code>GetAddress</code></li>\n<li>Call <code>Foo</code> with the literal <code>5</code> and the result of <code>GetSummary</code></li>\n<li>Assign this value to <code>a</code></li>\n</ul>\n'}, {'answer_id': 5412, 'author': 'OJ.', 'author_id': 611, 'author_profile': 'https://Stackoverflow.com/users/611', 'pm_score': 3, 'selected': False, 'text': '<p>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.</p>\n\n<p>In languages, like C++, where you can actually overload the behaviour of the &amp;&amp; and || operators, it is highly recommended that you <strong>do not do this</strong>. This is because when you overload this behaviour, you end up forcing the evaluation of both sides of the operation. This does two things:</p>\n\n<ol>\n<li>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.</li>\n<li>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.</li>\n</ol>\n\n<p>For more info, have a read of Scott Meyers\' book, <a href="https://rads.stackoverflow.com/amzn/click/com/020163371X" rel="noreferrer" rel="nofollow noreferrer">More Effective C++</a>. Cheers!</p>\n'}, {'answer_id': 5432, 'author': 'C. K. Young', 'author_id': 13, 'author_profile': 'https://Stackoverflow.com/users/13', 'pm_score': 1, 'selected': False, 'text': '<p>I like Orion\'s responses. I\'ll add two things:</p>\n\n<ol>\n<li>The left-to-right still applies first</li>\n<li>The inner-to-outer to ensure that all arguments are resolved before calling the function</li>\n</ol>\n\n<p>Say we have the following example:</p>\n\n<pre><code>a = Foo(5, GetSummary("Orion", GetAddress("Orion")),\n           GetSummary("Chris", GetAddress("Chris")));\n</code></pre>\n\n<p>Here\'s the order of execution:</p>\n\n<ol>\n<li><code>GetAddress("Orion")</code></li>\n<li><code>GetSummary("Orion", ...)</code></li>\n<li><code>GetAddress("Chris")</code></li>\n<li><code>GetSummary("Chris", ...)</code></li>\n<li><code>Foo(...)</code></li>\n<li>Assigns to <code>a</code></li>\n</ol>\n\n<p>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.</p>\n\n<p>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: <a href="http://www.gotw.ca/gotw/056.htm" rel="nofollow noreferrer">1</a>, <a href="http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.16" rel="nofollow noreferrer">2</a>. In answering the thread\'s question, however, <code>&amp;&amp;</code> and <code>||</code> are sequence points in C++ (unless overloaded; also see OJ\'s excellent answer). So some examples:</p>\n\n<ul>\n<li><code>foo() &amp;&amp; bar()</code></li>\n<li><code>foo() &amp; bar()</code></li>\n</ul>\n\n<p>In the <code>&amp;&amp;</code> case, <code>foo()</code> is guaranteed to run before <code>bar()</code> (if the latter is run at all), since <code>&amp;&amp;</code> is a sequence point. In the <code>&amp;</code> case, no such guarantee is made (in C and C++), and indeed <code>bar()</code> can run before <code>foo()</code>, or vice versa.</p>\n'}, {'answer_id': 5749, 'author': 'Brian Leahy', 'author_id': 580, 'author_profile': 'https://Stackoverflow.com/users/580', 'pm_score': 3, 'selected': False, 'text': '<p>&quot;C# : Left to right, and processing stops if a match (evaluates to true) is found.&quot;</p>\n<p>Zombie sheep is wrong.</p>\n<p>The question is about the &amp;&amp; operator, not the || operator.</p>\n<p>In the case of &amp;&amp; evaluation will stop if a FALSE is found.</p>\n<p>In the case of || evaluation stops if a TRUE is found.</p>\n'}, {'answer_id': 17521, 'author': 'Konrad Rudolph', 'author_id': 1968, 'author_profile': 'https://Stackoverflow.com/users/1968', 'pm_score': 0, 'selected': False, 'text': '<p><a href="https://stackoverflow.com/questions/5269/c-logic-order-and-compiler-behavior#5278">@csmba</a>:</p>\n<blockquote>\n<p>It was asked in a followup why or when would anyone use And instead of AndAlso (or &amp; instead of &amp;&amp;): Here is an example:</p>\n<pre><code>if ( x.init() And y.init()) then\n   x.process(y)\nend \ny.doDance()\n</code></pre>\n<p>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).</p>\n</blockquote>\n<p>I believe this is rather confusing. Although your example works, it\'s not the typical case for using <code>And</code> (and I would probably write this differently to make it clearer). <code>And</code> (<code>&amp;</code> 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:</p>\n<pre><code>Dim x As Formatting = Formatting.Bold Or Formatting.Italic\nIf (x And Formatting.Italic) = Formatting.Italic Then\n    MsgBox(&quot;The text will be set in italic.&quot;)\nEnd If\n</code></pre>\n'}, {'answer_id': 2641585, 'author': 'BCS', 'author_id': 1343, 'author_profile': 'https://Stackoverflow.com/users/1343', 'pm_score': 0, 'selected': False, 'text': '<p>The D programming language Does do <a href="http://www.digitalmars.com/d/1.0/expression.html#OrOrExpression" rel="nofollow noreferrer">left-to-right evaluation with short circuiting</a> and <a href="http://www.digitalmars.com/d/1.0/operatoroverloading.html#Future" rel="nofollow noreferrer">doesn\'t</a> allow overloading of the <a href="https://stackoverflow.com/questions/5269/c-logic-order-and-compiler-behavior/5412#5412"><code>&amp;&amp;</code> and \'||\'</a> operators.</p>\n'}]
['https://Stackoverflow.com/questions/5269', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/357/']