Frage

I am just testing out two simple expressions, although the opposite value yields the same result.

int main() {
    unsigned int a = 50, b = 33, c = 24, d = 12;

    if (a != b < c){
        /*a is not equal to b, so the bool is converted to 1 and 1 is less than c*/
        cout << "This is apparent" << endl;
    }

    if (a != b > c){
        /* a is not equal to b, so the bool is converted to one and 1 is not more than c.
         * The expression still evaluates to true.
         * Why is this? Is the compiler messing with something? */

        cout << "This is apparent" << endl;
    }

    return 0;
}
War es hilfreich?

Lösung

The only "funny business" is that the compiler is doing exactly what it's supposed to do.

<, >, and the other relational operators bind more tightly than = and !=, so this:

if (a != b < c)

is equivalent to this:

if (a != (b < c))

Since a is neither 0 nor 1, it will be unequal to the result of any equality or relational operator.

To compare the result of != to c, you can write:

if ((a != b) < c)

You should use parentheses when you're unsure of the relative precedence of the operators you're using, or when your readers are likely to be unsure. I know C pretty well, but I had to check the standard to be sure of the relative precedence of the relational and equality operators.

But in this particular case, I can't think of any reason to do what you're doing in the first place (other than as an exercise to understand expression evaluation, which is perfectly reasonable if that's what you're doing). If I saw if ((a != b) < c) in real-world code, I'd probably ask the author to rewrite it.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top