Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Optimizing if conditional statement

Is there a better way to write the below?

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

which means I cannot do

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading