Why does this next program print? Yes & rdquo; instead of & ldquo; No?

advertisements

Why does this following program print "Yes" instead of "No"?

None of the variables is initialized to 2.

    bool hello = 0;
    int a = 1;
    int b = 3;
    int c = 4;
    int d = 5;

    if (a || b || c || d == 2) {
        hello = 1;
    }

    if (hello == 1) {
        printf("Yes");
    }

    if (hello == 0) {
        printf("No");
    }

    return 0;
}


The statement

if (a || b || c || d == 2)

is equivalent to:

if (a != 0 || b != 0 || c != 0 || d == 2)

The equality comparison does not automatically distribute across all the variables. If you want to do that, you need to perform all the comparisons explicitly:

if (a == 2 || b == 2 || c ==2 || d == 2)