C Language

Lazy Logic

Yes, C is a devilishly clever little language. It's quick to write, too. Suppose you've written a function, get_customer, to return either an integer customer ID or zero if no customer is input. Why ywaste time with "verbose" code like

   custid = get_customer();
   if (custid > 0) {
      /* Process the customer */
   }

when you can simply write:

   if (custid = get_customer()) {
       /* Process the customer */
 }

With the original definition of get_customer, this code works. In C, an if statement evaluates the expression within parentheses, and, if the expression's value is non-zero, the subordinate code is executed. In this example, the variable custid is set to the return value of get_customer. Because the value of a C assignment operation is the same as the value assigned to the target variable, when custid is assigned a non-zero value, the subordinate code to process the customer is executed.

You'll see "simplified" if statement expressions like this all over C programs. But suppose you and your fellow programmers have been using get_customer for a while; say you have a dozen or so programs that call it. Then one day you get an I/O error that zaps one of your programs, and you decide you had better add to get_customer a return value of -1 for an I/O error. Problem solved? No, problems are created. Every

   if (custid = get_customer())

statement will still execute the subordinate code when there's an error because the value of the if statement expression is non-zero. On the other hand, if you follow the first rule and keep the assignment operation separate, your code will work properly with the new error return value.

C is a "truth-or-consequences" language. You'll experience less of the latter if you use only logical expressions (ones that evaluate to 0 or 1) in if statements. You can define the following simple macros to implement Boolean variables and functions that return a Boolean value.

   #define BOOL   int
   #define TRUE   1
   #define FALSE  0

You should also use only Boolean variables and functions with the logical operators && and ||. Following this practice eliminates problems caused by accidentally using the bitwise operators & and | in logical expressions.

by BrainBellupdated
Advertisement: