TIP: Click on subject to list as thread! ANSI
echo: c_echo
to: All
from: Bob Stout
date: 2003-09-11 09:51:10
subject: Re: Pointers

From: rbs{at}snippets.org
To: c_echo{at}yahoogroups.com

On Wed, 10 Sep 2003 Rob Swindell wrote:

> > Indeed, but how is it in C, with integers, I've defined TRUE as 1
> > and FALSE [as] 0, is
> >
> >         if(function(parm) == TRUE)
> >
> > necessary or could I use if(function(parm)) ?
>
> There's no assignment in that expression, so it's fine (without the ==
> TRUE).

It's arguably better without the comparison to true. The function could
return a non-zero, non-one value which should evaluate true, but won't. If
you insist on comparing to TRUE=1, you should use the TOBOOL macro from
SNIPTYPE.H...

#define TOBOOL(x) (!(!(x)))

...which will coerce any non-zero value to 1. E.g.

TOBOOL(0)  evaluates to 0/FALSE
TOBOOL(1)  evaluates to 1/TRUE
TOBOOL(37) evaluates to 1/TRUE
TOBOOL(-1) evaluates to 1/TRUE

>
> But if you did:
>
>            if(i=function(parm))
>
> Some compilers will generate a warning, so it's often better to use:
>
>            if((i=function(parm))==TRUE)  /* no warning */

This seems like a good time to remind folks of one of the oldest C
programming "tricks"... When doing comparisons, always put the constant on
the left side of the expression. For inequality and greater/less than
comparisons, it makes no difference, but it sure does when testing for
equality!

Since using "=" when you mean "==" is one of the most
common mistakes
(usually, it's a typo and is even made by experienced C programmers),
putting the constant on the left changes the compiler's action from a
warning to an error.

if (x == 6)	/* what you mean */

if (x = 6)	/* warning, possible unintended assignment */

if (6 = x)	/* error, assignment to a constant */

During early stages of testing, it's not uncommon to turn down the warning
level a bit or to simply ignore warnings if the program appears to compile
properly. This particular little typo can therefore quite easily slip past
you depending on the context and the specifics of your test data.

-------------------------------------------------------------
Consulting: http://www.MicroFirm.biz/
Web graphics development: http://Image-Magicians.com/
Software archives: http://snippets.org/snippets/
Audio and loudspeaker design:
  http://LDSG.snippets.org/
  http://www.diyspeakers.net/

--- SoupGate-Win32 v1.05
* Origin: rbs{at}snippets.org (2:292/516.666)
SEEN-BY: 633/267 270
@PATH: 292/516 854 140/1 106/2000 633/267

SOURCE: echomail via fidonet.ozzmosis.com

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.