473,698 Members | 2,274 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Logical And

sam
Please look at the code below
#include <stdio.h>

int expr(char str[], int i){
printf("%s \n",str);
return i;
}

int main()
{
if(expr("1st",1 ) || expr("2nd",0) && expr("3rd",1));
return 0;
}

output
-------
1st

As && has an higher precedence over ||
then it should call expr("2nd",0) or expr("3rd",0)
first then why it calls (expr("1st",1) first

Regards
Shiju
Nov 14 '05
34 2284
In <bu**********@n ews.tudelft.nl> Sidney Cadot <si****@jigsaw. nl> writes:
Eric Sosman wrote:
Sidney Cadot wrote:
Mark A. Odell wrote:
"osmium" <r1********@com cast.net> wrote in

Why on earth would you ever evaluate b if a is true?

If this wasn't a rhetorical question, I /could/ think of an answer. For
example: short-circuit evaluation may, under some circumstances,
negatively impact the size and/or speed of generated assembly code
(e.g., by introducing pipeline stalls).

You're missing the point, I think.


Umm no, I don't think so. I was merely following my instincts, which
invariably make me answer seemingly rhetorical questions.
Short-circuit evaluation isn't about efficiency, but about correctness.
The || and && operators are *defined* to work this way;
an implementation that evaluated `b' when `a' was true
would not be an implementation of C.


According to the "as if" principle, a compiler is perfectly free to do
this given the right circumstances. And, in fact, it may just be the
clever thing to do.


But the point is that it can do it *only* when the program can't tell
the difference. Fortran programmers often wish they could do things
like:

if (a == 0 || b / a > 0) /* do something */ ;

The short circuiting feature of || and && is not an optimisation feature,
its purpose is to make the language easier to use. Without it, the
above statement would have to be rewritten as:

if (a == 0) /* do something */ ;
else if (b / a > 0) /* do it again */ ;

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #21
Da*****@cern.ch (Dan Pop) writes:
[...]
The short circuiting feature of || and && is not an optimisation feature,
its purpose is to make the language easier to use.
above statement would have to be rewritten as:


I suspect it would be more accurate to say that it's not *just* an
optimization feature. Efficiency may also have been a concern when
the feature was first designed (probably in one of C's ancestors).

It's a happy coincidence that ease of use and efficiency (on the
hardware of the time) both led to the same design decision.

I haven't looked at the relevant historical documents lately, so I'm
only guessing here.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://www.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
Nov 14 '05 #22
In <ln************ @nuthaus.mib.or g> Keith Thompson <ks***@mib.or g> writes:
Da*****@cern.c h (Dan Pop) writes:
[...]
The short circuiting feature of || and && is not an optimisation feature,
its purpose is to make the language easier to use.
above statement would have to be rewritten as:


I suspect it would be more accurate to say that it's not *just* an
optimization feature. Efficiency may also have been a concern when
the feature was first designed (probably in one of C's ancestors).

It's a happy coincidence that ease of use and efficiency (on the
hardware of the time) both led to the same design decision.

I haven't looked at the relevant historical documents lately, so I'm
only guessing here.


I was using the *present* tense, so whatever was the case when the
feature was introduced is irrelevant to my statement.

As demonstrated in this thread, depending on the context, the feature
may or may not optimise the execution speed. I suspect this has always
been the case (in trivial cases, ORing/ANDing everything together is
faster than checking the value of each operand). In principle, the
compiler should be able to detect the cases when the as-if rule allows
non-short circuiting evaluation and and take advantage of it when it
improves the execution speed, but I doubt that many compilers bother
performing such checking.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #23
Keith Thompson wrote:
If I saw code that used "if (a & b)", my first assumption would be
that it was a typo for "if (a && b)", and my second would be that the
author really intended to test the bitwise "and" of a and b.


When writing something like "if (a & b)" it is a good idea to
write "if (a & b) /*bitwise*/" instead.
On the other hand it looks a little bit funny to me, just like
some beginner who writes "int i; /*an integer variable*/" ;-)

So I for myself always use "if (a bitand b)" instead of
"if (a & b)" (after including <iso646.h> of course),
because with this notation it should be obvious to see that I
did *really* mean & and not &&.

-rb
--
Ro************* @rbdev.net
Nov 14 '05 #24
Robert Bachmann <Ro************ *@rbdev.net> wrote in
news:40******** *************** @newsreader02.h ighway.telekom. at:
If I saw code that used "if (a & b)", my first assumption would be
that it was a typo for "if (a && b)", and my second would be that the
author really intended to test the bitwise "and" of a and b.


When writing something like "if (a & b)" it is a good idea to
write "if (a & b) /*bitwise*/" instead.


What's next? When writing this do we need the comment shown?

idx++; /* Increment 'idx' */

just because it might confuse a beginner? You, the developer must write
the code you intend to write. Why should I not believe you meant bit-AND
if you write?

if (reg_a_bits & reg_a_field_mas k)

What is so wrong about C that people aren't comfortable with it?

--
- Mark ->
--
Nov 14 '05 #25
"Mark A. Odell" <no****@embedde dfw.com> writes:
Robert Bachmann <Ro************ *@rbdev.net> wrote in
news:40******** *************** @newsreader02.h ighway.telekom. at:
If I saw code that used "if (a & b)", my first assumption would be
that it was a typo for "if (a && b)", and my second would be that the
author really intended to test the bitwise "and" of a and b.
When writing something like "if (a & b)" it is a good idea to
write "if (a & b) /*bitwise*/" instead.


What's next? When writing this do we need the comment shown?

idx++; /* Increment 'idx' */

just because it might confuse a beginner?


No, because "idx++;" is unambiguous.

The problem with "if (a & b)" is that it's as likely to be a newbie
mistake (using "&" where "&&" is correct) as a deliberate use of
bitwise-and. I'd rather add a comment than risk having the next
maintainer of the code (who may not be as comfortable with C as I am)
"correct" the "&" to "&&".
You, the developer must write the code you intend to write. Why
should I not believe you meant bit-AND if you write?

if (reg_a_bits & reg_a_field_mas k)


If the variables are called "reg_a_bits " and "reg_a_field_ma sk", it's
not as much of a problem. If they're called "a" and "b" -- well, they
probably shouldn't be unless it's a toy example.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://www.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
Nov 14 '05 #26
Keith Thompson <ks***@mib.or g> wrote in
news:ln******** ****@nuthaus.mi b.org:

[snip]
The problem with "if (a & b)" is that it's as likely to be a newbie
mistake (using "&" where "&&" is correct) as a deliberate use of
bitwise-and. I'd rather add a comment than risk having the next
maintainer of the code (who may not be as comfortable with C as I am)
"correct" the "&" to "&&".


In my world of microcontroller s and drivers, & is more common than &&.
You, the developer must write the code you intend to write. Why
should I not believe you meant bit-AND if you write?

if (reg_a_bits & reg_a_field_mas k)


If the variables are called "reg_a_bits " and "reg_a_field_ma sk", it's
not as much of a problem. If they're called "a" and "b" -- well, they
probably shouldn't be unless it's a toy example.


So the real fix might better to continue to write C without junk comments
but to pick variable names that have meaning? I'm all for that.

--
- Mark ->
--
Nov 14 '05 #27
> > > if(expr("1st",1 ) || expr("2nd",0) && expr("3rd",1));

Summary: Operator precedence governs the meaning of an
expression with multiple operators, but does not control
the order in which the operands are evaluated.


Finally a sensible answer in this thread. A corollary is: If you
want to use complex logical expressions, parenthise them so there
is NO DOUBT, NO DOUBT WHATSOEVER, what they mean. You will save a
lot of headaches, both your own and others.


(((((How) (would) (that) (help))?) (The (expressions (
((A || B) && C)
(and)
(A || (B && C))
) (have) ((the) (same) ((order) (of) (evaluation))). )
((There) (was) (never) ((any) (doubt) (about) (((the) (meaning))
(of) ((the) (expression)))) )).
Nov 14 '05 #28
Mark A. Odell wrote:
Robert Bachmann <Ro************ *@rbdev.net> wrote in
When writing something like "if (a & b)" it is a good idea to
write "if (a & b) /*bitwise*/" instead. What's next? When writing this do we need the comment shown?
idx++; /* Increment 'idx' */
just because it might confuse a beginner?

No. My point was that someone (a new code maintainer for example)
who reads code like "if (a & b)" can be in doubt that I really
wanted to bitwise-and "a" and "b".

I've often seen code like "if (a & b)" where the developer
actually should have written "if (a && b)".
So it always attracts my attention when I see code like "if (a & b)".
You, the developer must write the code you intend to write. Yes, but nobody is perfect :-)
Why should I not believe you meant bit-AND
if you write?
if (reg_a_bits & reg_a_field_mas k)

If I would have written "if (reg_a_bits & reg_a_field_mas k)"
it should be obvious to anyone that I really liked to bitwise-and
some bits with some mask.
In case "if (a & b)" it is not.
So picking up good (meaningful) variable names (as you already said)
is probably a better solution.

-rb
--
Ro************* @rbdev.net
Nov 14 '05 #29
Robert Bachmann wrote:
Keith Thompson wrote:
If I saw code that used "if (a & b)", my first assumption would be
that it was a typo for "if (a && b)", and my second would be that
the author really intended to test the bitwise "and" of a and b.


When writing something like "if (a & b)" it is a good idea to
write "if (a & b) /*bitwise*/" instead.

On the other hand it looks a little bit funny to me, just like
some beginner who writes "int i; /*an integer variable*/" ;-)

So I for myself always use "if (a bitand b)" instead of
"if (a & b)" (after including <iso646.h> of course),
because with this notation it should be obvious to see that I
did *really* mean & and not &&.


I rarely use the ISO646 stuff, because it seems to bring out the
worst in diehard key savers. When I do, I would prefer to use
'and' for &&, and just & for the bitwise stuff. What I really
want out of ISO646 is and, or, xor, not. These make code much
more readable. They also help to enforce minimum intersymbol blank
standards.

--
Chuck F (cb********@yah oo.com) (cb********@wor ldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net> USE worldnet address!
Nov 14 '05 #30

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

Similar topics

6
44106
by: Hari Om | last post by:
Here are the details of my error log files: I execute the command and get following message at console: ---------------------------------------------------------------------- ../sqlldr scott/tiger@common control=/full_path/test.ctl log=/full_path/adhoc/test.log SQL*Loader: Release 9.2.0.1.0 - Production on Tue Sep 2 10:49:27 2003 Copyright (c) 1982, 2002, Oracle Corporation. All rights reserved.
7
2894
by: Charles Crume | last post by:
Hello all; I have used dBASE, and other computer languages/databases, for years. They all have a logical field type. However, the version of MySQL used by the ISP hosting my site does not support a "logical" field type. It does support ENUM and I have set some up in a couple of tables that accept the values 'T' and 'F'. Sometimes they work like a logical field: if ($myrow) echo 'New';
80
35101
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.
3
1572
by: serge | last post by:
How do I determine which method I should use if I want to optimize the performance of a database. I took Northwind's database to run my example. My query is I want to retrieve the Employees' First and Last Names that sold between $100,000 and $200,000. First let me create a function that takes the EmployeeID
4
3552
by: serge | last post by:
I am running a query in SQL 2000 SP4, Windows 2000 Server that is not being shared with any other users or any sql connections users. The db involves a lot of tables, JOINs, LEFT JOINs, UNIONS etc... Ok it's not a pretty code and my job is to make it better. But for now one thing I would like to understand with your help is why the same SP on the same server and everything the same without me changing anything at all in terms of SQL...
14
36851
by: blueboy | last post by:
Hi, I am planning to automate a nighty restore of a DB on another server can someone point me in the right direction with the SQL script to modify the logical file names to the correct path and not the ones carried over with the DB?? i.e the database is to be renamed on the new server any help much appreciated
2
5541
by: dbtwo | last post by:
Until today I always thought as long as you see a lot of logical reads as compared to physical reads, then you're good. But it looks like it isn't so. But doesn't logical read mean it's being read from memory and no I/O involved? So why is Logical Reads = CPU Consumption ? I ran into an exact scenario last week when our applciation were running something, and each time an application started, the CPU would go from 99% idle to 48% idle. I...
1
1948
by: ags5406 | last post by:
Hi -- I posted this in a Fortran group but thought I'd post here as well. Any help is appreciated. I have a IVF10 DLL that is the calculation engine for a frontend application written in VB.NET 2005. I've noticed that when I pass a Boolean/Logical from VB.NET to IVF10 as part of an argument list, when I try to evaluate it it only
11
4686
by: Dominic Vella | last post by:
I am using MS-Access2000. I can't seem to set the default values for Logical type fields. I start with Dim dbsTmp As Object ' I think it's DAO.Database Set dbsTmp = DBEngine.OpenDatabase(CurrentProject.path & "\data_be.mdb") and then use the following to run my SQL ststement dbsTmp.Execute ----------------------------------------------------- Something like this SQL statement works: "ALTER TABLE tblStudent ADD COLUMN student_number...
7
3555
by: raylopez99 | last post by:
I have a logical drawing space much bigger than the viewport (the screen) and I'd like to center the viewport (the screen) to be at the center of the logical drawing space. After following the excellent transforms specified on Bob Powell's site, I still wonder if there's an easier way of centering it than the following procedure? Here is what I do now (it's awkward but it works): 1) I follow the transforms specified on Bob Powell's...
0
8672
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
8600
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
9156
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
9021
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
8892
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
8860
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
6518
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...
1
3038
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
2323
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.