简体   繁体   中英

C++ logical operator Q

This question might seem very noobish but my question is this: are these two statements logically the same?

int a;
int b;
int c;


if (!a && !b && !c)
//do something



if (!(a || b || c))
//do something

A truth table is useful to understanding logics.

#include <iostream>

using std::cout;
using std::endl;

int main(void) {
    int a;
    int b;
    int c;
    bool differ = false;

    cout << "a b c x y\n";
    for (a = 0; a <= 1; a++) {
        for (b = 0; b <= 1; b++) {
            for (c = 0; c <= 1; c++) {
                bool x = (!a && !b && !c);
                bool y =  (!(a || b || c));
                differ = differ || (x != y);
                cout << a << " " << b << " " << c << " " << x << " " << y << "\n";
            }
        }
    }
    if (differ) {
        cout << "they differ" << endl;
    } else {
        cout << "they are the same" << endl;
    }
    return 0;
}

Actually they are the same thanks to De Morgan's laws:

  !a && !b && !c
= !(a || b) && !c
= !((a || b) || c)
= !(a || b || c)

( = here is not the C++ assignment operator)

No. On your first statement, all conditions must be met. && operator means All should be true to make the result true otherwise it would be false. On your second statement, If one or more condition is true, then the condition would be done.

Sorry for a very brief explanation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM