TRUE and FALSE

Jo Are Rosland jar at ifi.uio.no
Thu Sep 6 21:32:59 AEST 1990


In article <3686 at goanna.cs.rmit.oz.au>, ok at goanna.cs.rmit.oz.au (Richard A. O'Keefe) writes:
> Let's not forget the Lisp Lesson:  there is often something useful you
> could return instead of an anonymous "true".  For example, if you are
> looking for a character in a string, instead of returning TRUE (it is
> there) or FALSE (it isn't) you could return a pointer to if it it's
> there or NULL if it isn't.  If you program with that in mind, you really
> don't _care_ much about TRUE/FALSE -vs- 1/0, because it's rare that you
> have so little to say.

Exactly!  Some examples of this from Lisp, are:

	(or a b)
	(and a b)

which evaluate to either nil, or the value of a or b.

Why can't I do this in C?  The && and || operators are defined
to return either 0 or 1.  With the Lisp semantics I could write
code like:

	return f() || g();

instead of:

	a = f();
	if (a)
		return a;
	else
		return g();

This is useful eg. when f() and g() return pointers (maybe in
some sort of search, where we only want to call the second
function if the first one fails.)  And I even think the first
version reads better.

So why does && and || return 0 or 1?  What would break if they were
less restrictive?  Operators like <, >, ==, which are most often used
in conjunction with && and ||, return 0 or 1 anyway.

-- 
_____________________
 |/   Jo Are Rosland
 [)   joare at sdata.no



More information about the Comp.lang.c mailing list