473,854 Members | 1,818 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Order Of Evaluation Question

der
Hello all,

I've a question about order of evaluations in expressions that have && and
|| operators in them.

The question is: will the evalution go left-to-right, no matter what -- even
if the || operator is before the && operator? e,g,
In an expression like a = (z>x) || (x<0) && (z-y>9);

is it guaranteed that z>x will be checked first?
is there a difference between expressions thats have || and && operators,
then those who don't?
in this expression: a = f() + g(); it isn't guaranteed that f() will be
called first, so I want to know whether it is the same with || and &&
operators.

Thanks for your help.
Nov 13 '05 #1
8 3353
<lähetetty & postitettu>

der wrote:
I've a question about order of evaluations in expressions that have && and
|| operators in them.

The question is: will the evalution go left-to-right, no matter what --
even if the || operator is before the && operator?
No, operator precedence dictates the evaluation order, only logical
operations at same precedence level are executed left-to-right.
In an expression like a = (z>x) || (x<0) && (z-y>9);

is it guaranteed that z>x will be checked first?
No, it's guaranteed that x<0 is evaluated first.
is there a difference between expressions thats have || and && operators,
then those who don't?


Yes.

--
Markku Kolkka
ma***********@i ki.fi
Nov 13 '05 #2
der <de*@noemail.co m> wrote:
# Hello all,
#
# I've a question about order of evaluations in expressions that have && and
# || operators in them.
#
# The question is: will the evalution go left-to-right, no matter what -- even
# if the || operator is before the && operator? e,g,
# In an expression like a = (z>x) || (x<0) && (z-y>9);

In an expression like (p) || (q), (p) will be evaluated and only if false will
(q) be evaluated. For (p) && (q), (q) is only evaluated if (p) is true. && has
a higher precedence that ||, so the fully parenthesised version of your predicate
is
(z>x) || ((x<0) && (z-y>9))
so the evaluation order is
valueof (z>x) || ((x<0) && (z-y>9))
= if (z>x)
then true
else
valueof (x<0) && (z-y>9)
= if (x<0)
then
if (z-y>9)
then true
then false
else false

# is it guaranteed that z>x will be checked first?
# is there a difference between expressions thats have || and && operators,
# then those who don't?

'||', '&&', '?:', and ',' serialise the evaluation of operands. '||', '&&', and
'?:' might not evaluate all their operands. ',' serialises, evaluating its left
operand and then its right. Other operators do not have a standardised order of
evaluation, and they will evaluate all operands but the order of loads and
stores to do side effects is not defined by the standard.

--
Derk Gwen http://derkgwen.250free.com/html/index.html
I'm not even supposed to be here today.
Nov 13 '05 #3
In article <3f******@news. 012.net.il>, der <de*@noemail.co m> wrote:
Hello all,

I've a question about order of evaluations in expressions that have && and
|| operators in them.

The question is: will the evalution go left-to-right, no matter what -- even
if the || operator is before the && operator? e,g,
In an expression like a = (z>x) || (x<0) && (z-y>9);

is it guaranteed that z>x will be checked first?
|| and && are special.

For both || and &&, it is guaranteed that the left side is evaluated
first, and all side effects of the left side will happen. Then the right
side will _only_ be evaluated if necessary; if you write (1 || <expr>)
or (0 && <expr>) then it is absolute hundred percent guaranteed that the
right side will _not_ be evaluated.
is there a difference between expressions thats have || and && operators,
then those who don't?
in this expression: a = f() + g(); it isn't guaranteed that f() will be
called first, so I want to know whether it is the same with || and &&
operators.

Nov 13 '05 #4

"pete" <pf*****@mindsp ring.com> wrote in message
news:3F******** ***@mindspring. com...
Markku Kolkka wrote:
In an expression like a = (z>x) || (x<0) && (z-y>9);

is it guaranteed that z>x will be checked first?


No, it's guaranteed that x<0 is evaluated first.


Please help me debug my program.
According to what you just said, the output should be
"Markku Kolkka is making sense."
but instead it says
"What the hell are you talking about?"
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
int a;
int z = -1;
int x = -2;
int y = 0;

a = (puts("What the hell are you talking about?"),
exit(EXIT_FAILU RE), z>x)
||
(puts("Markku Kolkka is making sense."), x<0)
&&
(z-y>9);

return 0;
}

--
pete


This is an example of trying to compress your code into too few lines and
then suffering the consequences. Try expanding the code a bit, I'll bet
you'll find the problem.

--
MiniDisc_2k2
Nov 13 '05 #5
On Sat, 12 Jul 2003 11:00:05 -0400, in comp.lang.c , "MiniDisc_2 k2"
<Ma******@nospa m.com> wrote:
This is an example of trying to compress your code into too few lines and
then suffering the consequences. Try expanding the code a bit, I'll bet
you'll find the problem.


I think pete knows that, its an ironic post.
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.c om/ms3/bchambless0/welcome_to_clc. html>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Nov 13 '05 #6
In article <3f******@news. 012.net.il> der <de*@noemail.co m> wrote:
I've a question about order of evaluations in expressions that have && and
|| operators in them.
Several others have given correct answers (and one person a wildly
wrong one :-) ). C does have a rule that is relatively easy to
remember here, though, and I think no one has yet described it.
That rule is: evaluation order is specified *only* by what C calls
"sequence points".

A compiler's job is to take some source-language description of
"what should happen" and re-arrange it, remove some of it, add to
it, and so on, so that some kind of computer hardware can make it
run as fast as possible. This slicing-and-dicing of your code is
allowed as long as the result is still what you originally asked
for. C compilers get to do this "cheaply" by piling up as much
action as they can between these "sequence points".

A sequence point is where the action stops. Stopping the action
makes "everything so far" finish, before the computer can go on to
"everything afterward". In other words, it establishes a particular
order of operations. (The compiler can still "slice and dice" your
code about, even across these sequence points, but *only* if it
can prove that you will not be able to tell that it has done so.
For instance, if you print output, that output must somehow magically
erase if it should not have been printed after all, and so on.)

This makes sequence points absolutely crucial, because as a C
programmer, you *need* to make sure things happen in specific
sequences. If you want to add 1 to i, or change p to point to
p->next, you *have* to have that happen before you use the new
values in i and p.

So the general answer to your question is that order of evaluation
is defined only if you have some of these "sequence points". Given
a sequence point, and some operation A that happens "before" and
some operation B that happens "after" that sequence point, every
C compiler must do A first, then do B (or, if it secretly slices
and dices things so that they happen simultaneously or in the other
order, it has to arrange an illusion, so that A *seems* to happen
before B, no matter what really goes on inside the machine).
in this expression: a = f() + g(); it isn't guaranteed that f() will be
called first...
Correct. Formally, the "+" and "=" operators have no sequence
points at all. (The function calls do have "embedded" sequence
points, but they are no help because we have no idea which function
gets called first.)
The question is: will the evalution go left-to-right, no matter
what -- even if the || operator is before the && operator? e,g,
In an expression like a = (z>x) || (x<0) && (z-y>9);

is it guaranteed that z>x will be checked first?


Here you are in luck. The C standard (either C89 or C99, there is
no real change here) says that the logical operators have sequence
points, and that given an expression with a logical operator, the
left hand side is evaluated first, then you get the sequence point.
If the result of the operator is now known, the right hand side is
not evaluated at all. (This "skip the other half if we know the
answer" technique is usually called "short-circuit evaluation".
Some other languages provide short-circuit evaluation too. For
instance, in Ada, one can write "if a and then b" to mean "test a;
then, only if the answer is not yet known, test b". Leaving out
the "then" -- "if a and b" -- allows the compiler to test both.
Paradoxically, it is actually sometimes faster to test both than
to skip one of the tests. These kinds of details are machine-dependent
though.)

Note that:

a = (z>x) || (x<0) && (z-y>9);

parses as:

a = (z > x) || ((x < 0) && ((z - y) > 9));

That is, the "&&" binds more tightly than the "||", and the "-"
in "z - y" binds more tightly than the ">" in "... > 9". So
what we have is a logical-OR-expression whose right hand side
is a logical-AND-expression. If you were to write instead:

a = ((z > x) || (x < 0)) && ((z - y) > 9);

you would have a logical-AND-expression whose left hand side
is a logical-OR-expression. Interestingly, while this changes
the overall result (and thus sometimes skips a different set
of evaluations), this has no effect on the evaluation *order*
if all sub-expressions are evaluated. (Exercise: why? Remember
that the rule is: "evaluate left side, then have a nice nap at a
sequence point, then evaluate right side only if necessary".)
--
In-Real-Life: Chris Torek, Wind River Systems (BSD engineering)
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://67.40.109.61/torek/index.html (for the moment)
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 13 '05 #7
In article <YnVPa.2545$zd4 .1300@lakeread0 2>,
"MiniDisc_2 k2" <Ma******@nospa m.com> wrote:
"pete" <pf*****@mindsp ring.com> wrote in message
news:3F******** ***@mindspring. com...
Markku Kolkka wrote:
> In an expression like a = (z>x) || (x<0) && (z-y>9);
>
> is it guaranteed that z>x will be checked first?

No, it's guaranteed that x<0 is evaluated first.


Please help me debug my program.
According to what you just said, the output should be
"Markku Kolkka is making sense."
but instead it says
"What the hell are you talking about?"
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
int a;
int z = -1;
int x = -2;
int y = 0;

a = (puts("What the hell are you talking about?"),
exit(EXIT_FAILU RE), z>x)
||
(puts("Markku Kolkka is making sense."), x<0)
&&
(z-y>9);

return 0;
}

--
pete


This is an example of trying to compress your code into too few lines and
then suffering the consequences. Try expanding the code a bit, I'll bet
you'll find the problem.


This is an example of completely missing the joke. Read the original
post, Markku's reply, and this point, and try to understand what is
going on here. If you don't get the joke, I will be quite willing to
explain it.
Nov 13 '05 #8
Markku Kolkka wrote:
der wrote:
I've a question about order of evaluations in expressions that have && and
|| operators in them.
The question is: will the evalution go left-to-right, no matter what --
even if the || operator is before the && operator?
No, operator precedence dictates the evaluation order, only logical
operations at same precedence level are executed left-to-right.


Wherever did you get that idea?

As a general rule, operator precedence does *not* dictate
evaluation order, and imagining that it does is a sure way to
get yourself in trouble. Mis-answering a question like this is
not the usual result of the mistaken assumption that operator
precedence does dictate evaluation order, but I guess it's
still a confirming instance of the general rule.

See http://www.eskimo.com/~scs/readings/...oe.960725.html
for more on this.
In an expression like a = (z>x) || (x<0) && (z-y>9);
is it guaranteed that z>x will be checked first?


Yes.
No, it's guaranteed that x<0 is evaluated first.


No.

Steve Summit
sc*@eskimo.com

297433826360262 691320794783426 50468004927
Nov 13 '05 #9

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

Similar topics

16
697
by: Bhushit Joshipura | last post by:
This post contains one question and one proposal. A. May I know why order of evaluation of arguments is not specified in C/C++? I asked a question in comp.lang.c++ for the following possibility and because the languages do not specify the order of evaluation, doing so was an error. int B::f ( int i, int j = i + 1 ) { // j defaults to i + 1
13
2673
by: Richard | last post by:
Boy, I'll sure bet this is a FAQ. Many years ago, my "runtime behavior of programming languages" prof absolutely guaranteed that C parameters are evaluated left-to-right. He was a bright guy from CMU whose research focus was on programming languages, and I believed him, but now I'm not so sure. Little help?
15
2954
by: Jens.Toerring | last post by:
Hi, I have a possibly rather stupid question about the order of evaluation in a statement like this: result = foo( x ) - bar( y ); How can I make 100% sure that foo(x) is evaluated before bar(y), where foo() and bar() can be either functions or macros? I got into problems with this when writing some hardware-related stuff where foo() and bar()
4
2581
by: Frank Wallingford | last post by:
Note: For those with instant reactions, this is NOT the common "why is i = i++ not defined?" question. Please read on. I came across an interesting question when talking with my colleagues. According to the standard, most operators evaluate their operands in an unspecified order. This means that in code like this: f() + g()
3
2819
by: andreas ames | last post by:
Hi all, recently I came across a line of code like the following: if seq.erase(seq.begin(), seq.end()) != seq.end() /* ... */ It made me wonder if this is just bogus or if it even can invoke undefined behaviour.
10
3330
by: nachch | last post by:
Does the C specification define the order of evaluation of assignment statements? For example, what should be the output from the following: int foo1() { printf("foo1\n"); return 0; } int foo2() { printf("foo2\n"); return 0; } int foo3() { printf("foo3\n"); return 0; } int main()
15
1976
by: Jeroen | last post by:
Hi all, I've got a very specific question about the evaluation order in C++. Assume some kind of custom array class, with an overloaded subscript operator. In the following code: { my_array a, b, c; a = b + c;
7
2504
by: Peter | last post by:
I know the order of construction of member and base class objects. My question is the following: Is the order of evaluation of argument lists for these constructors also defined? E.g. can I assume that the following code is exceptions safe? Assuming that the constructor of A, B or C may throw? Can I assume that B is created after the constructor of m_sA has been called?
54
3974
by: Rasjid | last post by:
Hello, I have just joined and this is my first post. I have never been able to resolve the issue of order of evaluation in C/C++ and the related issue of precedence of operators, use of parentheses. 1) "The order of evaluation of subexpressions is determined by the precedence and grouping of operators."
0
9750
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11023
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...
0
10672
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10740
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,...
1
7909
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
7076
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5738
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...
1
4550
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
4147
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.