TonyRomero
TonyRomero

Reputation: 182

Express a truth table using a single if-condition

My code looks like this:

/*
 * A B
 * 0 0 -> 1
 * 0 1 -> 0
 * 1 0 -> 0
 * 1 1 -> 0
 */

#define A condition_1
#define B condition_2

if (A) {
    // do nothing
} else {
    if (B) {
        // do nothing
    } else {
        // do something
    }
}

Above I've reported the truth table for two conditions where 1 is true and 0 is false, is there a way to express the truth table into a single if-condition?

Upvotes: 0

Views: 354

Answers (3)

Dialecticus
Dialecticus

Reputation: 16761

If there is only one 1 in the table then it's essentially AND operation. If there is only one 0 then it's OR operation. If there are two of both then you can make it an equality operation.

When you know which operation to chose your next step is to figure out which operands should be negated. For AND both operands must turn to 1 to produce 1 (1 AND 1 = 1), so negate those who would otherwise produce 0. For OR it's opposite, negate those who would produce 1 when trying to have 0 a s result (0 OR 0 = 0)

For equality operation bear in mind that bool can either be true or false, so there are only two values. If you try to use something that is not a bool for a logical operand then there would be problems. With that in mind when you want to produce equality negate any of the operands if originally they don't produce correct result (0 == 0 = 1 and also 1 == 1 = 1, if you understand me).

In your particular case we have only one 1 in the table so it's an AND operation. Both operands are 0 for this 1 outcome so we have to negate both of them:

!A && !B

Upvotes: 1

Ronaldd
Ronaldd

Reputation: 56

Use:

if (!A && !B) {
    // do something
}

Think, your truth table only returns 1 when both conditions are false (0 0 -> 1). You can use ! in both to invert it.

Upvotes: 4

Yksisarvinen
Yksisarvinen

Reputation: 22176

Your truth table represents a NOR (not or) operation. You can get that easily by combining logical NOT (!) with logical OR (||)

if (!(A || B)) {

}

PS. Please, don't use #define macros. It's very error-prone and tends to bite programmers who use it. Most often there are safer and more readable ways to perform what macro does.

Upvotes: 5

Related Questions