Home > OS >  Optimizing if conditional statement
Optimizing if conditional statement

Time:06-23

Is there a better way to write the below?

if ((A && B) || (A && B && C)) { ... }

which means I cannot do

if ((A && B) || C) { ... }

CodePudding user response:

You can use logical rules to simplify the statement:

(A && B) || (A && B && C)

Factorizing the common part (A && B) you get:

(A && B) && (true || C)

And of course true || C is always true so that entire group becomes a "don't care" and can be discarded. That leaves just:

A && B

There are other ways to arrive at the same result. In this case, even writing out a basic truth table would have made it pretty obvious.

For more complicated expressions, the use of a Karnaugh Map can be helpful.

  • Related