C Language

Precedence Without Precedent

In our get_customer example, you might think the following alternative would be safe and still have a nice "C-food" flavor.

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

Now the code guards against negative, as well as zero, return values. Or does it? Something's fishy here. This code simply assigns 0 or 1 to custid because the > comparison operator has higher precedence (i.e., binds more tightly) than the assignment operator. This code is equivalent to

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

What you really need is:

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

C has 15 levels of operator precedence (so much for C being a "simple" language). Two other easy rules will keep you from floundering at C. Do all assignments as separate statements, not as a part of a more complex expression. And use parentheses liberally to explicitly define the order of evaluation.

by BrainBellupdated
Advertisement: