473,795 Members | 3,481 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

&& 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
20 8156
rl*@hoekstra-uitgeverij.nl (Richard Bos) wrote in message news:<40******* **********@news .individual.net >...
ke***********@y ahoo.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.goo gle.com>
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 "subsequent ly 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\nresul t = 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*****@mindsp ring.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*****@mindsp ring.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.He lsinki.FI> wrote in message news:<Pi******* *************** *************** @melkinpaasi.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*****@mindsp ring.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***********@y ahoo.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

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

Similar topics

20
11375
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
3065
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 == desiredValue)
8
2819
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);" TextBox2.Attributes.Add("onKeyPress", jscode) You will notice that jscode contains the JavaScript Logical And operator (&&). However, ASP.NET renders this as &amp;&amp; in the code that is
9
3749
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'); printf("%d", a); /* code end */ 2
9
1755
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
9672
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...
1
10164
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
10001
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
7538
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
6780
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
5437
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
5563
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3723
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2920
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.