delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/08/07/14:35:23

From: Charles Krug <charles AT pentek DOT com>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: [Q] expression evaluation order
Date: Thu, 07 Aug 1997 09:10:59 +0100
Lines: 56
Message-ID: <33E98313.6250@pentek.com>
References: <5sbb1h$kvr$1 AT newton DOT pacific DOT net DOT sg>
NNTP-Posting-Host: mail.pentek.com
Mime-Version: 1.0
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

Victor wrote:
> 
> Is it safe to assume that the expression
> 
> if(first_function()==OK && second_function()==OK &&
> third_function()==OK) return(OK);
> 
> will be evaluated from left to right?
> 
> Regards.
> Victor Fesenko

No.

I think that ANSI tries to demand left-to-right evalutaion of &&.  But
not all compilers do this correctly.  To guarantee left-to-right
evaluation, you need:

if (first() == OK)	{
	if (second() == OK)	{
		if (third() == OK)	{
			return (OK);
		}
	}
}
return (!OK);

This suggests a better (IMO) implementation that's a bit more clear:
if (first() != OK)
	return (!OK);
else if (second != OK)
	return (!OK);
else if (third() != OK)
	return (!OK);
else
	return (OK);
 
Don't bother trying to save mythical machine cycles by placing all your
logicals on the same line.  Remember that function calls are much more
expensive than logicals in terms of processor time.  This is especially
true of x86 processors, which are notoriously slow in terms of stack
performance.

The professional in me would also like to see comments explaining what
first(), second(), and third() do, just in case you put this project
away for a year.  This is much easier to accomplish when they are on
seperate lines.

The best explanation of the rules of precedence I've ever heard:

	"Multiply and divide before you add and subtract"

	"Put parentheses around everything else"

-- 
Charles Krug, Jr.

- Raw text -


  webmaster     delorie software   privacy  
  Copyright 2019   by DJ Delorie     Updated Jul 2019