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 2285
"Mark A. Odell" <no****@embedde dfw.com> writes:
[...] Nasty nothing. It's dog simple.
if (a || b)
Why on earth would you ever evaluate b if a is true? Very simple. I believe we need to think about sequence points here.
The && and || operators short-circuit because the standard says so.
It's not at all obvious that they need to. There are at least four
possible ways this could have been defined, and I think there are
languages that implement each of them:
1. The logical "and" and "or" operators (however they're spelled)
always short-circuit (C, C++, Perl, etc.).
2. The "and" and "or" operators never short-circuit (Pascal, I think).
3. It's unspecified or implementation-defined whether they
short-circuit; code that assumes either that they do or that they
don't is potentially non-portable (I don't know of an example of
this).
4. The language provides variant forms, letting the programmer decide
whether short-circuiting is desired (Ada has "and" and "or", which
don't short-circuit, and "and then" and "or else", which do).
On modern CPUs, a non-short-circuiting form can actually improve
performance in some cases by avoiding pipeline stalls. The fact that
C doesn't provide an easy way to do this is partly a result of the
fact that the language was defined before pipeline stalls were much of
an issue.
I would geuss that some optimizing C compilers can transform "&&" and
"||" to non-short-circuiting forms if they can prove the RHS has no
side effects and doesn't depend on the LHS.
Of course short-circuiting is extremely useful for things like:
if (ptr != NULL && *ptr != 0) { ... }
--
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"
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. Consider:
int proof_of_concep t(void)
{
int a,b,c,d;
a = function_return ing_int()!=0;
b = function_return ing_int()!=0;
c = function_return ing_int()!=0;
d = function_return ing_int()!=0;
return a||b||c||d;
}
The best (fastest & shortest) translation of the return expression
evaluation for most architectures would be to just use the binary-or
operator on a, b, c, and d.
The alternative would involve a lot of branching, which is really
significantly slower on many architectures.
Whether any compiler is actually smart enough to do this: I doubt it!
Best regards, Sidney
Keith Thompson wrote: [...] On modern CPUs, a non-short-circuiting form can actually improve performance in some cases by avoiding pipeline stalls. The fact that C doesn't provide an easy way to do this is partly a result of the fact that the language was defined before pipeline stalls were much of an issue.
"C doesn't provide?" Perhaps you've forgotten
if (a || b) vs. if (a | b)
if (a && b) vs. if (a & b)
.... except that in some circumstances you might need to
write the last of these as `if (!!a & !!b)'. At any rate,
C does in fact provide non-short-circuited forms if you
want them.
-- Er*********@sun .com
Sidney Cadot wrote: 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, [...]
Ah, well, yes, of course. Perhaps I should have written
"An implementation that permitted the program to observe that
`b' had been evaluated ..." Schrödinger was a compiler writer
(at least, that's what Heisenberg may have said).
-- Er*********@sun .com
Eric Sosman wrote: Keith Thompson wrote:
[...] On modern CPUs, a non-short-circuiting form can actually improve performance in some cases by avoiding pipeline stalls. The fact that C doesn't provide an easy way to do this is partly a result of the fact that the language was defined before pipeline stalls were much of an issue.
"C doesn't provide?" Perhaps you've forgotten
if (a || b) vs. if (a | b) if (a && b) vs. if (a & b)
....And next time someone has the temerity to suggest that Pascal doesn't
provide short-circuit evaluation, I will be sure to point out the error
of their thinking by showing how it can be simulated in Pascal :-)
Personally, I wouldn't consider using bit-ops an easy way to emulate
non-short-circuit evaluation, given the interpretation of true as
"anything un-equal to zero". As you rightly point out, this can be
overcome by using !!x or (x!=0) for any boolean operand, but it's still
a bit clumsy, and quite error-prone. Proper operators for this would be
nice-to-have.
Best regards,
Sidney
Eric Sosman <Er*********@su n.com> writes: Keith Thompson wrote: [...] On modern CPUs, a non-short-circuiting form can actually improve performance in some cases by avoiding pipeline stalls. The fact that C doesn't provide an easy way to do this is partly a result of the fact that the language was defined before pipeline stalls were much of an issue.
"C doesn't provide?" Perhaps you've forgotten
if (a || b) vs. if (a | b) if (a && b) vs. if (a & b)
... except that in some circumstances you might need to write the last of these as `if (!!a & !!b)'. At any rate, C does in fact provide non-short-circuited forms if you want them.
If by "some circumstances" you mean "nearly all circumstances",
perhaps.
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. If there
were a comment explaining that it's really a logical "and", using "&"
rather than "&&" to avoid pipeline stalls, I'd spend a long time
trying to figure out (1) how it's known that the values of a and b
cannot be anything other 0 or 1, and (2) why the author thought this
micro-optimization was worth the time I'm spending thinking about it.
--
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"
On Tue, 13 Jan 2004 17:43:12 -0500, Eric Sosman <Er*********@su n.com>
wrote in comp.lang.c: Keith Thompson wrote: [...] On modern CPUs, a non-short-circuiting form can actually improve performance in some cases by avoiding pipeline stalls. The fact that C doesn't provide an easy way to do this is partly a result of the fact that the language was defined before pipeline stalls were much of an issue.
"C doesn't provide?" Perhaps you've forgotten
if (a || b) vs. if (a | b) if (a && b) vs. if (a & b)
... except that in some circumstances you might need to write the last of these as `if (!!a & !!b)'. At any rate, C does in fact provide non-short-circuited forms if you want them.
Yes, "!!" in C is the "Booleanization " operator for scalar types.
In C99:
if (_Bool(a) | _Bool(b))
....of course, bool may be substituted for _Bool if <stdbool.h> is
included.
--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++ http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Jack Klein wrote: In C99:
if (_Bool(a) | _Bool(b))
ITYM
if ((_Bool)a | (_Bool)b)
(assuming you got mixed up with C++ constructor syntax).
Jeremy.
Eric Sosman wrote: sam wrote: 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
"Operator precedence" and "order of evaluation" are two different things. Precedence dictates that the expression means
expr("1st",1) || ( expr("2nd",0) && expr("3rd",0) )
rather than
( expr("1st",1) || expr("2nd",0) ) && expr("3rd",0)
... but precedence alone doesn't determine the order in which the three expr() calls are made.
The evaluation order is determined not by the precedence, but by the definitions of the || and && operators. In this case, the rule for || says that if expr("1st",1) produces a non-zero value, the second sub-expression is not evaluated at all. If the expr("1st",1) yields zero, the second sub- expression *is* evaluated -- and in that evaluation, there is a similar rule for && that governs the order in which expr("2nd",0) and expr("3rd",0) are evaluated.
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.
--
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! This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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.
|
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';
|
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.
|
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
|
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...
| |
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
|
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...
|
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
|
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...
|
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...
|
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...
| |
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,...
|
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...
|
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,...
|
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...
|
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
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...
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
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...
| |