473,513 Members | 2,558 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Does (cond1 && cond2 && cond3) always evaluate left to right?

Hi There

Say I want to check if object1.Property1 is equal to a value, but
object1 could be null.

At the moment I have code like this:

if (object1 != null)
{
if (object1.Property == desiredValue)
{
//Do work here
}
}

Here is my question - Can I do this ...

if (object1 != null && object1.Property == desiredValue)
{
//Do work here
}

.... and be sure that conditions are always evaluated left to right and
the evaluation stops as soon as a condition evaluates to false ?

If I can collapse the conditions into one if statement, do you think
this is more or less elegant coding?

TIA
Bill

Nov 17 '05 #1
17 3026
Yes, you can.
The statements are evalueated from left to right. The most right condition
is not evaluated when one of the former conditions evaluates to false.

"or*******@yahoo.com.au" wrote:
Hi There

Say I want to check if object1.Property1 is equal to a value, but
object1 could be null.

At the moment I have code like this:

if (object1 != null)
{
if (object1.Property == desiredValue)
{
//Do work here
}
}

Here is my question - Can I do this ...

if (object1 != null && object1.Property == desiredValue)
{
//Do work here
}

.... and be sure that conditions are always evaluated left to right and
the evaluation stops as soon as a condition evaluates to false ?

If I can collapse the conditions into one if statement, do you think
this is more or less elegant coding?

TIA
Bill

Nov 17 '05 #2
Thanks Marinus

Nov 17 '05 #3
Also, nte that this behavior was specified in the original C language
definition, and carried over into C++, Java and C#. This is not particular
to one specific compiler, but a requirement for any compiler implementing
any of the C family of langauges.

--
--
Truth,
James Curran
[erstwhile VC++ MVP]

Home: www.noveltheory.com Work: www.njtheater.com
Blog: www.honestillusion.com Day Job: www.partsearch.com

<or*******@yahoo.com.au> wrote in message
news:11**********************@g47g2000cwa.googlegr oups.com...
Hi There

Say I want to check if object1.Property1 is equal to a value, but
object1 could be null.

At the moment I have code like this:

if (object1 != null)
{
if (object1.Property == desiredValue)
{
//Do work here
}
}

Here is my question - Can I do this ...

if (object1 != null && object1.Property == desiredValue)
{
//Do work here
}

... and be sure that conditions are always evaluated left to right and
the evaluation stops as soon as a condition evaluates to false ?

If I can collapse the conditions into one if statement, do you think
this is more or less elegant coding?

TIA
Bill

Nov 17 '05 #4

"James Curran" <ja*********@mvps.org> wrote in message
news:en**************@TK2MSFTNGP12.phx.gbl...
Also, nte that this behavior was specified in the original C language
definition, and carried over into C++, Java and C#. This is not
particular
to one specific compiler, but a requirement for any compiler implementing
any of the C family of langauges.

--
--
Truth,
James Curran
[erstwhile VC++ MVP]


Another note:

Although this is a C# group, I'm just pointing out that a similar method is
available in VB.Net as well:

Dim a As TextBox = Page.FindControl("MyControl")

If Not a Is Nothing And a.Text <> String.Empty
a.Text = "This is NOT empty!"
End If

The above would throw an exception (if a is nothing) because the "And"
keyword does not short-circuit the "If" statement. In order to
short-circuit in VB.Net you would use the keywords "AndAlso" or "OrElse".

Dim a As TextBox = Page.FindControl("MyControl")

If Not a Is Nothing AndAlso a.Text <> String.Empty
a.Text = "This is NOT empty!"
End If
HTH,
Mythran

Nov 17 '05 #5
(Yet another) note: C# also has operators & and | that do not perform
McCarthy evaluation (short-circuit). I'm not 100% sure, but I would
suspect that there is no guarantee in these cases that they evaluate
left-to-right.

&& and || will always stop as soon as the result of the expression is
determined. For && that means as soon as something evaluates false; for
|| that means as soon as something evaluates true, left-to-right.

Nov 17 '05 #6
"Bruce Wood" <br*******@canada.com> wrote in message
news:11**********************@g14g2000cwa.googlegr oups.com...
(Yet another) note: C# also has operators & and | that do not perform
McCarthy evaluation (short-circuit). I'm not 100% sure, but I would
suspect that there is no guarantee in these cases that they evaluate
left-to-right.
Consider:
if(MethodThatThrowsException() == true & MethodThatSetsVariable() == true)

The expected behaviour would be that MethodThatSetsVariable would not
execute.
&& and || will always stop as soon as the result of the expression is
determined. For && that means as soon as something evaluates false; for
|| that means as soon as something evaluates true, left-to-right.

Nov 17 '05 #7
Bruce Wood <br*******@canada.com> wrote:
(Yet another) note: C# also has operators & and | that do not perform
McCarthy evaluation (short-circuit). I'm not 100% sure, but I would
suspect that there is no guarantee in these cases that they evaluate
left-to-right.
Yes there is:

From the C# spec section 14.2.1 (ECMA numbering):

<quote>
Except for the assignment operators, all binary operators are left-
associative, meaning that operations are performed from left to right.
[Example: For example, x + y + z is evaluated as (x + y) + z. end
example]
</quote>

This is different to C/C++, which makes no such guarantee.
&& and || will always stop as soon as the result of the expression is
determined. For && that means as soon as something evaluates false; for
|| that means as soon as something evaluates true, left-to-right.


Yup.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #8
Thanks, Jon. You can tell I'm an old C hack, which is why I wasn't sure
about & and |. Nice to know that C# firmed that up.

Nov 17 '05 #9
Sean Hederman <em*******@codingsanity.blogspot.com> wrote:
"Bruce Wood" <br*******@canada.com> wrote in message
news:11**********************@g14g2000cwa.googlegr oups.com...
(Yet another) note: C# also has operators & and | that do not perform
McCarthy evaluation (short-circuit). I'm not 100% sure, but I would
suspect that there is no guarantee in these cases that they evaluate
left-to-right.


Consider:
if(MethodThatThrowsException() == true & MethodThatSetsVariable() == true)

The expected behaviour would be that MethodThatSetsVariable would not
execute.


Yes it would - the above does *not* do short-circuiting, whereas with a
&& the RHS wouldn't execute.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #10
Jon,

You missed Sean's point. Look at the method names. The left-hand side
would throw an exception, which would interrupt the control flow and so
the right-hand side would not execute.

However, you are correct: if the left-hand side did not throw an
exception then the right-hand side would always execute regardless of
to what value the left-hand side evaluated.

Nov 17 '05 #11
Bruce Wood <br*******@canada.com> wrote:
You missed Sean's point. Look at the method names. The left-hand side
would throw an exception, which would interrupt the control flow and so
the right-hand side would not execute.
Ah, right. Yes, I did miss that completely :)
However, you are correct: if the left-hand side did not throw an
exception then the right-hand side would always execute regardless of
to what value the left-hand side evaluated.


Yup.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #12
In message <OU*************@TK2MSFTNGP12.phx.gbl>, Mythran
<ki********@hotmail.comREMOVETRAIL> writes
Another note:

Although this is a C# group, I'm just pointing out that a similar
method is available in VB.Net as well: The above would throw an exception (if a is nothing) because the "And"
keyword does not short-circuit the "If" statement. In order to
short-circuit in VB.Net you would use the keywords "AndAlso" or "OrElse".


How utterly vile.

I'd forgotten about that whole bunfight over backwards compatibility
with VB6.

--
Steve Walker
Nov 17 '05 #13
> <quote>
Except for the assignment operators, all binary operators are left-
associative, meaning that operations are performed from left to right.
[Example: For example, x + y + z is evaluated as (x + y) + z. end
example]
</quote>>
This is different to C/C++, which makes no such guarantee.
&& and || will always stop as soon as the result of the expression is
determined. For && that means as soon as something evaluates false; for
|| that means as soon as something evaluates true, left-to-right.


Yup.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Actually C/C++ does guarantee this. But operator precedence takes over as it
does in C# as well. 1 + 4 * 2 does not equal 10 in either language. If all
operators are equal precedence they will evaluate left to right just like
func1() && func2() will short circuit in C#/C++/C. Just because operator
precedence is not understood does not mean that C/C++ will evaluate from
right to left.

Nov 17 '05 #14
Lorad <je*********@hotmail.come> wrote:
Actually C/C++ does guarantee this. But operator precedence takes over as it
does in C# as well. 1 + 4 * 2 does not equal 10 in either language. If all
operators are equal precedence they will evaluate left to right just like
func1() && func2() will short circuit in C#/C++/C. Just because operator
precedence is not understood does not mean that C/C++ will evaluate from
right to left.


I was under the impression (and it's one which I've seen repeated in
several places by knowledgable people) that although most individual
compilers specify the order of evaluation, it's not in the standard.

Reading Stroustrup (2nd ed) I can find where , && and || guarantee that
the left-hand operand is evaluated before the right-hand operand, but
nothing more than that. The fact that those ones are *specifically*
guaranteed implies to me that the rest aren't.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #15
Lorad <je*********@hotmail.come> wrote:
Actually C/C++ does guarantee this. But operator precedence takes over as it
does in C# as well. 1 + 4 * 2 does not equal 10 in either language. If all
operators are equal precedence they will evaluate left to right just like
func1() && func2() will short circuit in C#/C++/C. Just because operator
precedence is not understood does not mean that C/C++ will evaluate from
right to left.


I was under the impression (and it's one which I've seen repeated in
several places by knowledgable people) that although most individual
compilers specify the order of evaluation, it's not in the standard.

Reading Stroustrup (2nd ed) I can find where , && and || guarantee that
the left-hand operand is evaluated before the right-hand operand, but
nothing more than that. The fact that those ones are *specifically*
guaranteed implies to me that the rest aren't.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #16
You are arguing two different things. Consider:

int One() { printf ("1"); return 1;}
int Two() { printf ("2"); return 2;}
int Four() { printf ("4"); return 4;}

int x = One() + Four() * Two();

In C/C++:
We CAN be absolutely certain that afterwards, x will equal 9.
We CANNOT be absolutely certain that "142" will be printed. It may print
"421", "214" etc.

However, in C# I believe we can assume that "142" will be printed (assuming
appropriate changes to the output routine were made).

The individual terms will be evaluated in any order, while the expression as
a whole will be evaluated according to precedence. Further in C/C++ (but,
again, not in C#), the compiler may assume infinite precision, and ignore
redundant parentheses.:

int a = (x * y) / z;

The compiler is allowed to that as "a = x * (y / z)", which is
equivalent --- unless y is small and z large, so that (y/z) goes to zero in
an int.

--
Truth,
James Curran
[erstwhile VC++ MVP]

Home: www.noveltheory.com Work: www.njtheater.com
Blog: www.honestillusion.com Day Job: www.partsearch.com

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Lorad <je*********@hotmail.come> wrote:
Actually C/C++ does guarantee this. But operator precedence takes over as it does in C# as well. 1 + 4 * 2 does not equal 10 in either language. If all operators are equal precedence they will evaluate left to right just like func1() && func2() will short circuit in C#/C++/C. Just because operator
precedence is not understood does not mean that C/C++ will evaluate from
right to left.


I was under the impression (and it's one which I've seen repeated in
several places by knowledgable people) that although most individual
compilers specify the order of evaluation, it's not in the standard.

Reading Stroustrup (2nd ed) I can find where , && and || guarantee that
the left-hand operand is evaluated before the right-hand operand, but
nothing more than that. The fact that those ones are *specifically*
guaranteed implies to me that the rest aren't.

Nov 17 '05 #17
James Curran <ja*********@mvps.org> wrote:
You are arguing two different things. Consider:

int One() { printf ("1"); return 1;}
int Two() { printf ("2"); return 2;}
int Four() { printf ("4"); return 4;}

int x = One() + Four() * Two();

In C/C++:
We CAN be absolutely certain that afterwards, x will equal 9.
We CANNOT be absolutely certain that "142" will be printed. It may print
"421", "214" etc.
Yes.
However, in C# I believe we can assume that "142" will be printed (assuming
appropriate changes to the output routine were made).
Yes.
The individual terms will be evaluated in any order, while the expression as
a whole will be evaluated according to precedence. Further in C/C++ (but,
again, not in C#), the compiler may assume infinite precision, and ignore
redundant parentheses.:

int a = (x * y) / z;

The compiler is allowed to that as "a = x * (y / z)", which is
equivalent --- unless y is small and z large, so that (y/z) goes to zero in
an int.


I'm not sure where this comes into our discussion though - I was just
saying that C# *does* guarantee that

x & y

will evaluate x first, then y - but that C/C++ makes no guarantee.

Lorad was claiming that if all the operators are of equal precedence,
C/C++ guarantee that the operands are evaluating from left to right. I
believe that's true of && and ||, but not of other operators.
Precedence will still be obeyed in terms of the operations themselves,
but the order in which the operands are evaluated is an entirely
separate matter.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #18

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

Similar topics

3
3592
by: mitsura | last post by:
Hi, I have included a small listing. The test program opens a panel and show a bitmap. What I want is to when the mouse is over the bitmap panel, I want to trap the left mouse click. The...
8
38618
by: A.M | last post by:
Hi, Using C#, what is the equivalent of functions Left, Right and Mid that we had in vb6? Thanks, Alan
0
1850
by: mehul | last post by:
CheckBox template always evaluate to False even if checked in a DataGrid hosted inside a TabStrip in ASP.NET Hi, I am trying to develop an ASP.NET application. I am using TabStrip (which is...
11
5091
by: Bruce A. Julseth | last post by:
I have: If (Microsoft.VisualBasic.Left(TextBox1.Text, 1) = "$") Then TextBox1.Text = Microsoft.VisualBasic.Right(TextBox1.Text, TextBox1.Text.Length - 1) End If Adding: Imports...
3
6452
by: Ed Chiu | last post by:
Hi, Does C# has functions such as replace, left, right, substring for strings? Without these functions, it's not easy to process strings. TIA
6
2210
by: James Brown [MVP] | last post by:
Hi, I am having trouble understanding how the 'const' modifier affects the 'left-right' rule when deciphering c-declarations: const int *x; // x is a pointer to a 'const int' int const *x; ...
8
4600
by: Chaitanya | last post by:
Hello, In my Application i want to know when user clicks both the "Left" and "Right" buttons of the Mouse. I am getting a number like this "3145728". But the MouseButtons Enum contains only Left,...
0
1411
by: garfieldsevilla | last post by:
I have a report in Access 2003 which consists of a header with two fields and a subform pasted into the centre. When I open this form, it always displays in Print Preview and I cannot find an...
0
7260
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,...
1
7099
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...
0
7525
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...
0
5685
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
5086
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...
0
3233
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...
0
3222
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1594
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 ...
1
799
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.