473,769 Members | 1,752 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Logical vs. Conditional Logical Operators in C#

Hi all,

I'm having an argument with a co-worker about the difference between
the & and && operators when applied to boolean operands in C#. His
point of view is that the expression (false & expr2) might be optimised
at JIT-time and the second expression will not be evaluated. In my
opinion this would break the contract of the C# language if the JIT
compiler were to remove the call to expr2 entirely. I'm not saying that
it's good programming practice to depend on the side effects of expr2's
evaluation, all I'm saying is that it just feels _right_ to know that
both sides of the logical expression were evaluated.

I'd really appreciate any input from some of the CLR gurus out there.
Is there a difference between these operators in IL? Might a JIT
compiler conceivably shortcut the evaluation? Any other things I
missed?

Thanks,

Jono

May 5 '06 #1
10 18023
When using the && operator the compilier uses short circuit logic, e.g.
it the first oparand is false, the second one is not evaluated. This can
be used in statements like:

if (str != null && str.Length != 0) ...

This is safe, as the second operand is not evaluated it the reference is
null. If both operands were evaluated, the second would throw an
NullReferenceEx ception if the reference was null.

When using the & operator, both operands are always evaluated.
Jonathan wrote:
Hi all,

I'm having an argument with a co-worker about the difference between
the & and && operators when applied to boolean operands in C#. His
point of view is that the expression (false & expr2) might be optimised
at JIT-time and the second expression will not be evaluated. In my
opinion this would break the contract of the C# language if the JIT
compiler were to remove the call to expr2 entirely. I'm not saying that
it's good programming practice to depend on the side effects of expr2's
evaluation, all I'm saying is that it just feels _right_ to know that
both sides of the logical expression were evaluated.

I'd really appreciate any input from some of the CLR gurus out there.
Is there a difference between these operators in IL? Might a JIT
compiler conceivably shortcut the evaluation? Any other things I
missed?

Thanks,

Jono

May 5 '06 #2
Jonathan <jo*******@gmai l.com> wrote:
I'm having an argument with a co-worker about the difference between
the & and && operators when applied to boolean operands in C#. His
point of view is that the expression (false & expr2) might be optimised
at JIT-time and the second expression will not be evaluated. In my
opinion this would break the contract of the C# language if the JIT
compiler were to remove the call to expr2 entirely. I'm not saying that
it's good programming practice to depend on the side effects of expr2's
evaluation, all I'm saying is that it just feels _right_ to know that
both sides of the logical expression were evaluated.

I'd really appreciate any input from some of the CLR gurus out there.
Is there a difference between these operators in IL? Might a JIT
compiler conceivably shortcut the evaluation? Any other things I
missed?


Both sides are evaluated with &. As you say, only evaluating one side
would be breaking the language spec. (If the JIT notices that it's
completely without side-effects, it could do some optimisation - but
you'd have to look at the generated code to know for sure.)

With &&, it's guaranteed that the RHS won't be evaluated if the LHS is
false.

This (and its equivalent for "or") allows for things like:

if (x==null || x.Length==0)

to be safe.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
May 5 '06 #3
It's the other way around.

false && expr2 is guaranteed never to evaluate expr2, just as
true || expr2 is guaranteed never to evaluate expr2.

whereas

false & expr2 is guaranteed to always evaluate expr2, just as
true | expr2 is guaranteed always to evaluate expr2.

The && and || operators are referred to as using McCarthy evaluation
(for us old-timers) or more recently "short-circuit" evaluation. In
general the && and || forms are preferred, and it is common C, C++, and
C# idiom to say things like:

if (myObject != null && myObject.BoolPr operty)
{
... do something ...
}

May 5 '06 #4
JIT compiler will not shortcut the evaluation, C# compiler will - for both
&& and &, it will not even compile the if clause.

void Test(bool b)
{
if (false & b)
{
Console.WriteLi ne("foo");
}
else
{
Console.WriteLi ne("boo");
}
}

gets compiled by csc into the following IL:

..method private hidebysig instance void Doo(bool b) cil managed
{
.maxstack 8
L_0000: ldstr "boo"
L_0005: call void [mscorlib]System.Console: :WriteLine(stri ng)
L_000a: ret
}

"Jonathan" <jo*******@gmai l.com> wrote in message
news:11******** **************@ u72g2000cwu.goo glegroups.com.. .
Hi all,

I'm having an argument with a co-worker about the difference between
the & and && operators when applied to boolean operands in C#. His
point of view is that the expression (false & expr2) might be optimised
at JIT-time and the second expression will not be evaluated. In my
opinion this would break the contract of the C# language if the JIT
compiler were to remove the call to expr2 entirely. I'm not saying that
it's good programming practice to depend on the side effects of expr2's
evaluation, all I'm saying is that it just feels _right_ to know that
both sides of the logical expression were evaluated.

I'd really appreciate any input from some of the CLR gurus out there.
Is there a difference between these operators in IL? Might a JIT
compiler conceivably shortcut the evaluation? Any other things I
missed?

Thanks,

Jono

May 5 '06 #5
"Jonathan" <jo*******@gmai l.com> wrote in message
news:11******** **************@ u72g2000cwu.goo glegroups.com.. .
Hi all,

I'm having an argument with a co-worker about the difference between
the & and && operators when applied to boolean operands in C#. His
point of view is that the expression (false & expr2) might be optimised
at JIT-time and the second expression will not be evaluated. In my
opinion this would break the contract of the C# language if the JIT
compiler were to remove the call to expr2 entirely. I'm not saying that
it's good programming practice to depend on the side effects of expr2's
evaluation, all I'm saying is that it just feels _right_ to know that
both sides of the logical expression were evaluated.

I'd really appreciate any input from some of the CLR gurus out there.
Is there a difference between these operators in IL? Might a JIT
compiler conceivably shortcut the evaluation? Any other things I
missed?

Thanks,

Jono


Well empirically && short circuits and & doesn;t (just tested it in VS2005).

If it makes the call in one situation it would be madness to sometimes not
make the call in others due to JIT optimization. The behavior of the code
would be non-deterministic depending on the mood of the JIT.

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk
May 5 '06 #6
The & operator does not use shortcut. What you demonstrate is compiler
optimization when one of the operands is a known value.

Lebesgue wrote:
JIT compiler will not shortcut the evaluation, C# compiler will - for both
&& and &, it will not even compile the if clause.

void Test(bool b)
{
if (false & b)
{
Console.WriteLi ne("foo");
}
else
{
Console.WriteLi ne("boo");
}
}

gets compiled by csc into the following IL:

.method private hidebysig instance void Doo(bool b) cil managed
{
.maxstack 8
L_0000: ldstr "boo"
L_0005: call void [mscorlib]System.Console: :WriteLine(stri ng)
L_000a: ret
}

"Jonathan" <jo*******@gmai l.com> wrote in message
news:11******** **************@ u72g2000cwu.goo glegroups.com.. .
Hi all,

I'm having an argument with a co-worker about the difference between
the & and && operators when applied to boolean operands in C#. His
point of view is that the expression (false & expr2) might be optimised
at JIT-time and the second expression will not be evaluated. In my
opinion this would break the contract of the C# language if the JIT
compiler were to remove the call to expr2 entirely. I'm not saying that
it's good programming practice to depend on the side effects of expr2's
evaluation, all I'm saying is that it just feels _right_ to know that
both sides of the logical expression were evaluated.

I'd really appreciate any input from some of the CLR gurus out there.
Is there a difference between these operators in IL? Might a JIT
compiler conceivably shortcut the evaluation? Any other things I
missed?

Thanks,

Jono


May 5 '06 #7
What I did was answering the question. The question was whether JIT
optimizes false & expr2, and compiler optimization gets involved in this
case, as I've written.

I would understand if the OP meant something different from what he had
written (e.g. "is expr2 evaluated if I type if (expr1 & expr2), if expr1
gets evaluated to false?"), but it was obvious to me that he asked about
evaluating & operator application to known "false" value and expression.

"Göran Andersson" <gu***@guffa.co m> wrote in message
news:eH******** ******@TK2MSFTN GP05.phx.gbl...
The & operator does not use shortcut. What you demonstrate is compiler
optimization when one of the operands is a known value.

Lebesgue wrote:
JIT compiler will not shortcut the evaluation, C# compiler will - for
both && and &, it will not even compile the if clause.

void Test(bool b)
{
if (false & b)
{
Console.WriteLi ne("foo");
}
else
{
Console.WriteLi ne("boo");
}
}

gets compiled by csc into the following IL:

.method private hidebysig instance void Doo(bool b) cil managed
{
.maxstack 8
L_0000: ldstr "boo"
L_0005: call void [mscorlib]System.Console: :WriteLine(stri ng)
L_000a: ret
}

"Jonathan" <jo*******@gmai l.com> wrote in message
news:11******** **************@ u72g2000cwu.goo glegroups.com.. .
Hi all,

I'm having an argument with a co-worker about the difference between
the & and && operators when applied to boolean operands in C#. His
point of view is that the expression (false & expr2) might be optimised
at JIT-time and the second expression will not be evaluated. In my
opinion this would break the contract of the C# language if the JIT
compiler were to remove the call to expr2 entirely. I'm not saying that
it's good programming practice to depend on the side effects of expr2's
evaluation, all I'm saying is that it just feels _right_ to know that
both sides of the logical expression were evaluated.

I'd really appreciate any input from some of the CLR gurus out there.
Is there a difference between these operators in IL? Might a JIT
compiler conceivably shortcut the evaluation? Any other things I
missed?

Thanks,

Jono


May 5 '06 #8
My question is, why would you want to evaluate more than you need to? If
the whole expression cannot possibly evaluate to true, then why would you
want to spend CPU cycles evaluating the rest of the expression?

If you want to ensure expr2 is called then you should explicitly call it
before the if statement

bool expr2Result = expr2;
if (false && expr2Result)... ...
I think that is much more clear than

if (false & expr2)

especially as someone may come along at a later date and change it to &&
because they think they are "optimising " the code!

Pete
May 5 '06 #9
> The question was whether JIT optimizes false & expr2, and compiler optimization gets involved in this case, as I've written.

No it does not. The following code:

class Start
{
private static bool SideEffectMetho d()
{
Console.WriteLi ne("Hello from SideEffectMetho d");
return true;
}

[STAThread]
static void Main(string[] args)
{
if (false & SideEffectMetho d())
{
Console.WriteLi ne("Hi here.");
}
}
}

Produces the output, "Hello from SideEffectMetho d", which it would not
if the expression were optimized by the compiler.

Changing the & to a && results in no output.

May 5 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

15
2278
by: Max | last post by:
Hi, I'm a perl programmer and am trying to learn PHP. So far I have figured out most of the differences, but have not been able to find out how to do the following: When running through a loop, how can you test two separate conditions against the same $element of an array. For example, this is how I thought it would be done (similar to Perl), but it did not work:
80
35133
by: Christopher Benson-Manica | last post by:
Of course one can get the effect with appropriate use of existing operators, but a ^^ operator would make for nice symmetry (as well as useful to me in something I'm working on). Am I the only one who would find it useful? -- Christopher Benson-Manica | I *should* know what I'm talking about - if I ataru(at)cyberspace.org | don't, I need to know. Flames welcome.
92
9899
by: Raghavendra R A V, CSS India | last post by:
hie.. Do any one knows how to write a C program without using the conditional statements if, for, while, do, switch, goto and even condotional statements ? It would be a great help for me if someone helps me... Urgent - Please reply soon ! Thanks, Raghu
6
2606
by: TB | last post by:
This is a repost of something I had posted four months ago with no response, I'm hoping to get some feedback... From the Microsoft .net Core Reference (pg. 104) C# shares the AND (short-circuit) operator (&&) with C and C++. This operator works with two operands, evaluating as 'true' if both operands are true. But later (pg. 124) Behind the scenes, the compiler combines the 'true', 'false',
3
12495
by: shdwsclan | last post by:
I am native to various languages but bitwise operators just kill me. I see how much I take object oriented languages for granted. I like all the other c derivitives but ANSI C is making me loose my hair....especially ANSI C's bitwise operators..... For reference i come from the (Java/C#/C++) realm and was never forced to use these. Many people dont understand these....I tried to make sense....I know the truth tables...and I can do simple...
48
536
by: spibou | last post by:
This concerns the Wikipedia article on C and C++ operators: http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B Until very recently the first table in the page was a very useful one on the precedence of C operators. This has recently been replaced by one on C++ operators. I'm not at all happy with that but I guess I can always link to the history page. But I was wondering if anyone could have a look and verify that the C part is...
5
2904
by: paulo | last post by:
Can anyone please tell me how the C language interprets the following code: #include <stdio.h> int main(void) { int a = 1; int b = 10; int x = 3;
8
1710
by: marcwentink | last post by:
To my surprise Visual Studio 8 - VB evaluates C_B in if C_A And C_B Then And Hence if C_B is an expression that can only be validated if C_A is true my code crashes. For example If p_EdType <"" And CLng(p_EdType) 0 Then ..... There is no Conditional-And operator in Visual Basic?
3
2478
by: somenath | last post by:
Hi All, I have one question regarding the conditional operator. In the draft C99 standard it is mentioned that "1 The following are the sequence points described in 5.1.2.3: -- The call to a function, after the arguments have been evaluated (6.5.2.2). -- The end of the first operand of the following operators: logical AND && (6.5.13);
0
9589
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10212
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9995
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9863
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7410
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5304
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5447
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3962
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3563
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.