One more point regarding = and == (more flamage)

Richard Harter rh at smds.UUCP
Tue Mar 26 20:45:53 AEST 1991


In article <15563 at smoke.brl.mil>, gwyn at smoke.brl.mil (Doug Gwyn) writes:

> Gee, I guess I'm not a C programmer, according to your criterion.

Now Doug, I may have hutzpah, but not enough to say anything like that.
:-)

> I have found to the contrary that introduction of an explicit Boolean
> type, used completely and consistently, makes C source more
> intelligible and more likely to be correct.

Would it shock you to learn my code regularly uses an explicit Boolean
type and that TRUE and FALSE are always defined?  I thought so.  However
that is not the really the issue at hand.

> I would agree with an assertion that a C programmer ought to fully
> understand the traditional mixed numerical and Boolean usage, but
> I don't recommend coding in such a style.

For the most part we probably agree.  In the case in point, however,
the issue is not really one of mixed numerical and Boolean usage.  The
C conditional really is one of testing between invalid (formally 0) and
valid (not 0).  Before someone objects that the test is numeric, think
again.  You can say if(pointer) or if(char).  While it is true that char's
can be converted to ints, pointers cannot be legitimately.

So what it comes down to is that when you have an expression 'if(x)..'
and x is not numeric you already have a situation where, for the purposes
of the test, x can only have two values, valid and invalid.  Transforming
it into 'if (x != 0)' is simply transforming it into 'if (boolean != false)'.
Would you say 'if ( (x==y) == true)'?

On the other hand, testing whether a numeric expression is 0 is bad practice
precisely because 0 is not an invalid number.  I.e. when I say 'if (x) '
and x is a pointer variable, I am testing whether x is valid as a pointer
whereas when I say 'if (x)' and x is a number I am really testing whether
x!=0 rather whether x is a valid number.  In such cases the code would
be distorting the meaning of the conditional.

-- 
Richard Harter, Software Maintenance and Development Systems, Inc.
Net address: jjmhome!smds!rh Phone: 508-369-7398 
US Mail: SMDS Inc., PO Box 555, Concord MA 01742
This sentence no verb.  This sentence short.  This signature done.



More information about the Comp.lang.c mailing list