Search code examples
c++if-statementconditional-statementstruthtable

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?


Solution

  • 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.