BOOLEAN as enum

Bob Stout Bob.Stout at p6.f506.n106.z1.fidonet.org
Fri Apr 6 00:30:07 AEST 1990


In an article of <4 Apr 90 15:45:52 GMT>, (Michael T. Sullivan) writes:

 >Okay, put another way "func() != FALSE" doesn't necessarily mean that
 >func() is true, since func() can now return ERROR.  Since when is something
 >true or false or something else?  It should either be true or false--there
 >are only two answers to a yes-or-no question.

  OK, but you ultimately have control over what func() returns so you have the  
ability to assure it returns either 1 or 0, just as you do now. This is why I  
suggested the BOOL macro, so you could write:

typdef enum {ERROR = -1, FALSE, TRUE} logical;
#define BOOL(x) (!(!(x)))

logical func()
{
        int x;
        ...
        if (bad_stuff)
                return ERROR;
        ...
        return BOOL(x);         /* always 1 or 0        */
}

main()
{
        int result;
        ...
        if (ERROR == (result = func()))
                handle_it();
        else if (TRUE == result)        /* BOOL obviates !FALSE tests   */
                do_true_stuff();
        else    do_false_stuff();
        ...
}

  Now if you're concerned about what func() returns, simply process the return  
value with BOOL and omit the error return. Since `logical' is a typedef of an  
enumeration, the values you assign are really nothing more than glorified  
#defines anyway - enum's evaluate to int's and can therefore assume any value  
whatsoever. Like any #defined value, if you don't want to use ERROR, no one's  
twisting your arm - it's just there if you want/need it. Don't criticize the  
shorthand when the language is incapable of expressing what you mean. 



More information about the Comp.lang.c mailing list