[comp.lang.c] Testing expressions -- some guidelines

minow@decvax.UUCP (Martin Minow) (07/16/87)

1. If the variable (or function) can only take on TRUE or FALSE use either
	if (xxx_flag) ...
   or	if (xxx_flag != FALSE) ...
   also www = (xxx_flag != FALSE) ? yyy : zzz;
   Note: the variable or function name should clearly indicate that this
   is a Boolean variable.  I.e., "isalpha()", or "output_flag".
   In a ?: expression, do not exploit the fact that, in C, a Boolean
   expression yields either 0 or 1.  This is a source of confusion.

2. Testing against a single bit:
	if ((xxx_datum & yyy_bit) != 0) ...
   Note the use of parentheses and an explicit != 0.  While this is
   redundant, keeping it in makes the logic of the program clear to
   the people who have to maintain it.  In some circumstances, I've written:
	#define BIT_SET(var, mask) ((var & mask) != 0)
	if (BIT_SET(xxx_datum, yyy_bit)) ...

3. Safety.  If you are concerned about hardware errors, the single bit
   difference between TRUE and FALSE and the all-zero value of FALSE
   offer unneccessary sources of danger. Instead, #define TRUE and FALSE
   to be non-zero values.  (I can't give guidance as to the proper choice
   of values.  The best choice would be to have unique values now TRUE and
   FALSE for each unique Boolean, but this may be impractical). Now:
	switch (xxx_flag) {
	case xxx_TRUE:
	    ...
	    break;
	case xxx_FALSE:
	    ...
   	    break;
	default:
	    fatal_error(...);
	}

Your task as a programmer is not to minimize typing, or to demonstrate
how well you understand C syntax; it is to write a message that can
be understood not only by the computer, but by your collegues.  If you
do your work correctly, you can take a program that you wrote 20 years
ago in a language that no longer exists, and use the algorithm to solve
a new problem.

Martin Minow
decvax!minow