Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!mnetor!uunet!seismo!husc6!panda!genrad!decvax!minow From: minow@decvax.UUCP (Martin Minow) Newsgroups: comp.lang.c Subject: Testing expressions -- some guidelines Message-ID: <116@decvax.UUCP> Date: Wed, 15-Jul-87 20:44:13 EDT Article-I.D.: decvax.116 Posted: Wed Jul 15 20:44:13 1987 Date-Received: Sat, 18-Jul-87 01:41:41 EDT References: <13851@watmath.UUCP> <7460@elsie.UUCP> <13891@watmath.UUCP> <23253@sun.uucp> <843@bsu-cs.UUCP> Reply-To: minow@decvax.UUCP (Martin Minow) Organization: Digital Eq. Corp. - Merrimack NH. Lines: 43 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