Tag Archives: boolean

Avoiding unnecessary branching

Practice: Avoiding unnecessary branching.

Example (in C):
   if (c == 'N')
   {
       b = TRUE;
   }
   else
   {
       b = FALSE;
   }

Discussion: Since C inherited the conditional expression from Algol 60, we could write instead:
   b = (c == 'N') ? TRUE : FALSE;
But even that is over-complicated when we could—and should—write:
   b = c == 'N';
Besides being simpler, this avoids branching, resulting in smaller and faster generated code.

Objection: It is convenient to set breakpoints on the “then” and “else” alternatives of the “if” statement when debugging.

Answer: One can break on the assignment statement and examine its result.

Copyright © 2008 Possum Technologies, All Rights Reserved.

Comparing booleans

Practice: Comparing a boolean literal to a boolean result.

Example (in C): Let b be some expression having a boolean value (say, v1 > v2).
   if (b) ...

is better than

   if (b == TRUE) ...

and

   if (!b) ...

is better than

   if (b == FALSE) ....

Discussion: Booleans are sometimes referred to as “conditionals” in pre-ANSI C and have the type LOGICAL in Fortran.  The ANSI C standard guarantees that the result of a comparison always returns either TRUE (1) or FALSE (0). So were we to write

   if ((v1 > v2) == TRUE) ...
we would be comparing v1 and v2, which comparison would result in either TRUE or FALSE, which is fine, but then we would be further comparing that TRUE-or-FALSE result with the literal boolean value TRUE, which adds nothing useful to the more succint
   if (v1 > v2) ...

Objection: Some suggest that comparisons of boolean results with TRUE or FALSE is more readable.

Answer: Were
   ((v1 > v2) == TRUE)
more readable than
   (v1 > v2),
it follows that
   (((v1 > v2) == TRUE) == TRUE)
would be even more readable, and
   ((((v1 > v2) == TRUE) == TRUE) == TRUE)
more readable still, with further “improvements” in readability left as an exercise to the reader.

Copyright  ©  2008 Possum Technologies, All Rights Reserved.