Tag Archives: branching

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.

Advertisements