473,395 Members | 1,504 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

&& and || Operator precedence enforcement

Hi Folks,
This question may well have been asked and answered before. But, sorry
that I couldn't find one from the archives.

I typed up this program and compiled it with gcc 3.3.2
main() {
int i = -3,j= 2,k=0,m;

m = ++i || ++j && ++k;
printf("\n%d %d %d %d\n",i,j,k,m);
}
and got the output to be
-2 2 0 1

I presumed that the answer should have well been
-3 3 1 1

as ++j and ++k would first be evaluated and && operator applied to
obtain the result to be TRUE (3 && 1). Hence, ++i wouldn't be evaluated
as one part of || goes TRUE.

The ANSI C specification clearly states that && has precedence over ||.

Could someone explain why this strange "-2 2 0 1" output for the program
is obtained?

Cheers
Vivek
Nov 14 '05 #1
20 8103
Vivek N wrote:

Hi Folks,
This question may well have been asked and answered before. But, sorry
that I couldn't find one from the archives.

I typed up this program and compiled it with gcc 3.3.2
main() {
int i = -3,j= 2,k=0,m;

m = ++i || ++j && ++k;
printf("\n%d %d %d %d\n",i,j,k,m);
}
and got the output to be
-2 2 0 1

I presumed that the answer should have well been
-3 3 1 1

as ++j and ++k would first be evaluated and && operator applied to
obtain the result to be TRUE (3 && 1).
Hence, ++i wouldn't be evaluated
as one part of || goes TRUE.

The ANSI C specification clearly states that &&
has precedence over ||.
(a || b && c), is the same as (a || (b && c)).
Could someone explain why this strange "-2 2 0 1"
output for the program is obtained?


j and k are not evaluated at all.

The left operand of || is evaluted before the right.
The right operand of || is evaluated conditionally only if
the left operand is equal to zero.
Your left operand (++i), is not equal to zero.
Your right operand (++j && ++k) is not evaluated.

--
pete
Nov 14 '05 #2
Vivek N <ke***********@yahoo.com> spoke thus:
main() {
Allowing the return type of a function to default to int is illegal in
C99 and dubious otherwise.
int i = -3,j= 2,k=0,m; m = ++i || ++j && ++k;
printf("\n%d %d %d %d\n",i,j,k,m);
Where is <stdio.h>? Turn up gcc's warnings (-Wall -pedantic -ansi).
Could someone explain why this strange "-2 2 0 1" output for the program
is obtained?


Not strange at all, thanks to short-circuit evaluation. The fact that
&& has precedence over || only means that the assignment to m is
equivalent to

m=++i || (++j && ++k);

++i is computed first, and if it is nonzero (true), then the entire
statement is guaranteed to be true regardless of what (++j && ++k) is.
In C, this means that (++j && ++k) will not be evaluated. That is
what short-circuit evaluation is, and that is why only i is
incremented in the code you posted.

--
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.
Nov 14 '05 #3
ke***********@yahoo.com (Vivek N) wrote:
as ++j and ++k would first be evaluated and && operator applied to
obtain the result to be TRUE (3 && 1). Hence, ++i wouldn't be evaluated
as one part of || goes TRUE.

The ANSI C specification clearly states that && has precedence over ||.


The ISO C specification states no such thing, since "precedence" is
ambiguous.
What it _does_ state is this:
* To begin with, all logical operators are evaluated left-to-right, with
short-circuit evaluation. This means that it's possible to do this:

if (ptr!=NULL && *ptr!='A') ...

and be certain that your pointer is tested before being dereferenced.
* The logical and (&&) operator binds more closely than the logical or
(||). That is, x || y && z means x || (y && z), not (x || y) && z. The
order of evaluation remains the same, however.

Richard
Nov 14 '05 #4
Richard Bos wrote:

<snip>

Richard,

I think your clock is incorrectly set.

The original message is dated 14:34:18 GMT (1) and your reply is dated
13:56:05 GMT (2).

(1) Date: 19 Jan 2004 06:34:18 -0800
(2) Date: Mon, 19 Jan 2004 13:56:05 GMT

Nov 14 '05 #5
Grumble <in*****@kma.eu.org> wrote:
Richard Bos wrote:

I think your clock is incorrectly set.
This is true (I've been looking for a gizmo that keeps it set to an
atomic clock, but I'm not paying $39.95 to some vague shareware firm for
it, so in the mean time I'm correcting it by hand every now and then)...
The original message is dated 14:34:18 GMT (1) and your reply is dated
13:56:05 GMT (2).


....but this doesn't necessarily indicate that. Usenet is weird.

Richard
Nov 14 '05 #6

"Vivek N" <ke***********@yahoo.com> wrote in message
news:e7************************@posting.google.com ...
Hi Folks,
This question may well have been asked and answered before. But, sorry
that I couldn't find one from the archives.

I typed up this program and compiled it with gcc 3.3.2
main() {
int i = -3,j= 2,k=0,m;

m = ++i || ++j && ++k;
printf("\n%d %d %d %d\n",i,j,k,m);
}
and got the output to be
-2 2 0 1

I presumed that the answer should have well been
-3 3 1 1

as ++j and ++k would first be evaluated and && operator applied to
obtain the result to be TRUE (3 && 1). Hence, ++i wouldn't be evaluated
as one part of || goes TRUE.

The ANSI C specification clearly states that && has precedence over ||.

The precedence of an operator only defines where brackets are implicitely
placed to avoid abiguity. Thus a || b && c evaluates to a || (b && c)
rather than (a || b) && c. But after that the conditional statement is
executed left to right and will abort as soon as it is know that the
condition is false, which is why the ++j and ++k are not evaluated. I've
seen some compilers with an option to force all expressions in a conditional
statement to be evaluated so check your compiler if you really need this ..

Sean
Nov 14 '05 #7
In <bu**********@news-rocq.inria.fr> Grumble <in*****@kma.eu.org> writes:
Richard,

I think your clock is incorrectly set.

The original message is dated 14:34:18 GMT (1) and your reply is dated
13:56:05 GMT (2).

(1) Date: 19 Jan 2004 06:34:18 -0800
(2) Date: Mon, 19 Jan 2004 13:56:05 GMT


How did you decide that the original message was correctly time stamped?

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #8
Dan Pop wrote:
Grumble wrote:
I think your clock is incorrectly set.

The original message is dated 14:34:18 GMT (1) and your reply is dated
13:56:05 GMT (2).

(1) Date: 19 Jan 2004 06:34:18 -0800
(2) Date: Mon, 19 Jan 2004 13:56:05 GMT


How did you decide that the original message was correctly time stamped?


The original message showed up on my system when I downloaded new
messages at approximately 14:40:00 GMT.

Then Pete's and Christopher's messages showed up on my system when I
downloaded new messages at approximately 14:55:00 GMT.

When Richard's message showed up 5 minutes later, I figured it was
more probable that the first 3 were correctly time-stamped, and it
was Richard's clock which was incorrectly set.

Are you satisfied with my answer? :-)

Nov 14 '05 #9
On 19 Jan 2004, Vivek N wrote:
m = ++i || ++j && ++k;

as ++j and ++k would first be evaluated and && operator applied to
obtain the result to be TRUE (3 && 1). Hence, ++i wouldn't be evaluated
as one part of || goes TRUE.
The ANSI C specification clearly states that && has precedence over ||.


Your reasoning doesn't make sense as ++ has even higher precedence than &&.
Nov 14 '05 #10
rl*@hoekstra-uitgeverij.nl (Richard Bos) wrote in message news:<40*****************@news.individual.net>...
ke***********@yahoo.com (Vivek N) wrote:
as ++j and ++k would first be evaluated and && operator applied to
obtain the result to be TRUE (3 && 1). Hence, ++i wouldn't be evaluated
as one part of || goes TRUE.

The ANSI C specification clearly states that && has precedence over ||.
The ISO C specification states no such thing, since "precedence" is
ambiguous.


How so?
...
* The logical and (&&) operator binds more closely than the logical or
(||). That is, x || y && z means x || (y && z), not (x || y) && z.


6.5p3: The grouping of operators and operands is indicated by the syntax.(71

71) The syntax specifies the precedence of operators in the evaluation of an
expression, ...

6.5.13:
logical-AND-expression:
inclusive-OR-expression
logical-AND-expression && inclusive-OR-expression

What's the difference between 'binds' and precedence?

--
Peter
Nov 14 '05 #11
Sean Kenwrick wrote:
The precedence of an operator only defines where brackets are
implicitely placed to avoid abiguity. Thus a || b && c evaluates
to a || (b && c) rather than (a || b) && c. But after that the
conditional statement is executed left to right and will abort as
soon as it is known that the condition is false, which is why the
++j and ++k are not evaluated. I've seen some compilers with an
option to force all expressions in a conditional statement to be
evaluated so check your compiler if you really need this ..


If one wanted to force all expressions in a conditional statement to
be evaluated, instead of

a || b && c

I believe one could write

(a != 0) | (b != 0) & (c != 0)

Nov 14 '05 #12
Sean Kenwrick wrote:
The precedence of an operator only defines where brackets are
implicitely placed to avoid abiguity. Thus a || b && c evaluates
to a || (b && c) rather than (a || b) && c. But after that the
conditional statement is executed left to right and will abort as
soon as it is known that the condition is false, which is why the
++j and ++k are not evaluated. I've seen some compilers with an
option to force all expressions in a conditional statement to be
evaluated so check your compiler if you really need this ..


If one wanted to force all expressions in a conditional statement to
be evaluated, instead of

a || b && c

I believe one could write

(a != 0) | (b != 0) & (c != 0)

Nov 14 '05 #13
Nudge wrote:
If one wanted to force all expressions in a conditional statement to
be evaluated, instead of

a || b && c

I believe one could write

(a != 0) | (b != 0) & (c != 0)


a = 1
b = 0
c = 0

((a != 0) | (b != 0) & (c != 0)) = 0
((a != 0) | ((b != 0) & (c != 0))) = 1

--
pete
Nov 14 '05 #14
In article <news:63*************************@posting.google.c om>
Peter Nilsson <ai***@acay.com.au> writes:
[regarding the grammar in the C Standard and a certain footnote]
What's the difference between 'binds' and precedence?


In computer-language-parsing jargon, none. In compiler work
"binding" is a more general term; one might refer to "early" vs
"late" "binding" of names in linkage, for instance. In ordinary
conversational English, however, the word "bind" avoids the
connotation that "precedence" gives. Specifically, by talking
about how some operator might "bind left to right", we can avoid
having the reader see this as "subsequently proceed to operate in
sequence at runtime".

The phrase "operator precedence" is literally made up of the words
"operator precede" plus a few extra letters ("nce"), from which
one might assume that if "a + b * c" gives the multiplication
operator "precedence", then the entire "b * c" part will "precede"
any and all of the "a +" part. But in fact, if one runs the
following C code:

#include <stdio.h>

int f(void), g(void), h(void);

int main(void) {
printf("result = %d\n", f() + g() * h());
return 0;
}

int f(void) { puts("f"); return 3; }
int g(void) { puts("g"); return 4; }
int h(void) { puts("h"); return 5; }

the only *requirements* are that the output contain the three lines
"f", "g", and "h" (in any order) followed by "result = 23". The
"g" and "h" lines need not come out first -- f() can run first,
for instance, even though the addition at least appears to happen
last -- and in fact, using gcc on the x86, I get:

% cc -O -o u u.c -W -Wall -ansi -pedantic
% ./u
f
g
h
result = 23

Adding parentheses around g() * h() will usually have no effect
(not really surprising, since the multiplication operator is already
bound to the result of the two function calls, and parentheses need
only affect the parse binding). The only way to *force* g() and
h() to run before f() is to use C's runtime sequencing tools, called
"sequence points". For instance:

int t1, t2;
t1 = g();
t2 = h();
t1 *= t2;
t1 += f();

(and the corresponding change to the "result =" line) will force
the output to be "g\nh\nf\nresult = 23\n".

The complete list of sequence points can be found in the C standard,
and a summary in the FAQ.
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 14 '05 #15
In article <40***********@mindspring.com>,
pete <pf*****@mindspring.com> wrote:
Nudge wrote:
If one wanted to force all expressions in a conditional statement to
be evaluated, instead of

a || b && c

I believe one could write

(a != 0) | (b != 0) & (c != 0)


a = 1
b = 0
c = 0

((a != 0) | (b != 0) & (c != 0)) = 0
((a != 0) | ((b != 0) & (c != 0))) = 1


Nope. Those are both 1.

-- Brett
Nov 14 '05 #16
Brett Frankenberger wrote:

In article <40***********@mindspring.com>,
pete <pf*****@mindspring.com> wrote:
Nudge wrote:
If one wanted to force all expressions in a conditional statement to
be evaluated, instead of

a || b && c

I believe one could write

(a != 0) | (b != 0) & (c != 0)


a = 1
b = 0
c = 0

((a != 0) | (b != 0) & (c != 0)) = 0
((a != 0) | ((b != 0) & (c != 0))) = 1


Nope. Those are both 1.


Thank you.

--
pete
Nov 14 '05 #17
Jarno A Wuolijoki <jw******@cs.Helsinki.FI> wrote in message news:<Pi*************************************@melk inpaasi.cs.Helsinki.FI>...
On 19 Jan 2004, Vivek N wrote:
m = ++i || ++j && ++k;

as ++j and ++k would first be evaluated and && operator applied to
obtain the result to be TRUE (3 && 1). Hence, ++i wouldn't be evaluated
as one part of || goes TRUE.
The ANSI C specification clearly states that && has precedence over ||.


Your reasoning doesn't make sense as ++ has even higher precedence than &&.


Folks, Thanks for all your inputs. The following statement by Sean in
this thread, throws some better light for me on this issue:

"The precedence of an operator only defines where brackets are
implicitely
placed to avoid abiguity. Thus a || b && c evaluates to a || (b && c)
rather than (a || b) && c. But after that the conditional statement
is
executed left to right and will abort as soon as it is know that the
condition is false, which is why the ++j and ++k are not evaluated.
I've
seen some compilers with an option to force all expressions in a
conditional
statement to be evaluated so check your compiler if you really need
this .."

Thanks Sean, and all others.
Nov 14 '05 #18
In article <40***********@mindspring.com>,
pete <pf*****@mindspring.com> wrote:
Nudge wrote:
If one wanted to force all expressions in a conditional statement to
be evaluated, instead of

a || b && c

I believe one could write

(a != 0) | (b != 0) & (c != 0)


a = 1
b = 0
c = 0

((a != 0) | (b != 0) & (c != 0)) = 0
((a != 0) | ((b != 0) & (c != 0))) = 1


That would be quite surprising, unless the C Standard has changed the
precedence of & and | and nobody told me.
Nov 14 '05 #19
ai***@acay.com.au (Peter Nilsson) wrote:
rl*@hoekstra-uitgeverij.nl (Richard Bos) wrote in message news:<40*****************@news.individual.net>...
ke***********@yahoo.com (Vivek N) wrote:
as ++j and ++k would first be evaluated and && operator applied to
obtain the result to be TRUE (3 && 1). Hence, ++i wouldn't be evaluated
as one part of || goes TRUE.

The ANSI C specification clearly states that && has precedence over ||.


The ISO C specification states no such thing, since "precedence" is
ambiguous.


How so?


It is generally assumed by newbies to imply both order of evaluation
_and_ closeness of binding, as demonstrated by the OP.

Richard
Nov 14 '05 #20
In <40***********************@news.free.fr> Nudge <de*****@kma.eu.org> writes:
Dan Pop wrote:
Grumble wrote:
I think your clock is incorrectly set.

The original message is dated 14:34:18 GMT (1) and your reply is dated
13:56:05 GMT (2).

(1) Date: 19 Jan 2004 06:34:18 -0800
(2) Date: Mon, 19 Jan 2004 13:56:05 GMT


How did you decide that the original message was correctly time stamped?


The original message showed up on my system when I downloaded new
messages at approximately 14:40:00 GMT.

Then Pete's and Christopher's messages showed up on my system when I
downloaded new messages at approximately 14:55:00 GMT.

When Richard's message showed up 5 minutes later, I figured it was
more probable that the first 3 were correctly time-stamped, and it
was Richard's clock which was incorrectly set.

Are you satisfied with my answer? :-)


Looks like a perfect non-sequitur to me. There is no connection between
the order Usenet messages arrive at one site and the order in which they
were posted. So, it is perfectly possible that the original message was
incorrectly time stamped and that Richard was the first person to post a
reply to it, even if you got other replies before his. No need to assume
that the other messages were incorrectly time stamped in order to validate
this scenario.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #21

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

Similar topics

20
by: William | last post by:
Original question: "Give a one-line C expression to test whether a number is a power of 2. " Answer: if (x && !(x & (x-1)) == 0) My question: Why does this expression work?
17
by: orekinbck | last post by:
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 ==...
8
by: Nathan Sokalski | last post by:
I add a JavaScript event handler to some of my Webcontrols using the Attributes.Add() method as follows: Dim jscode as String = "return (event.keyCode>=65&&event.keyCode<=90);"...
9
by: marko | last post by:
/* code start */ int a = 0; /* expected evaluation and excution order with precedence in mind /* False(3) , True(1), False(2) */ if ( (a=1) == 0 || 0 != 1 && (a =2) == 1) putchar('T');...
9
by: find clausen | last post by:
How can I use this: if (!zxmes && self.name != "menu") and add if (zmes == 1) if (!zxmes && self.name != "menu" || zmes == 1) and make it work.
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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,...
0
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...
0
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...

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.