Frank Tian
Frank Tian

Reputation: 807

How to do equal comparison in C or C++?

I am just wondering in C or C++, for the expression:

b == c || b == d

Can I do something like:

b == (c || d)

and get the same behavior?

Upvotes: 4

Views: 195

Answers (2)

Keith Thompson
Keith Thompson

Reputation: 263667

No, operators in C and C++ don't implicitly distribute over subexpressions like that. Evaluation is defined strictly in terms of the direct association of operators with operands. There are no "shortcuts" as you might have in mathematics or English.

If you write code that incorrectly assume such implicit distribution, you're likely to end up with an expression that's syntactically and semantically valid, but that doesn't do what you expect.

The || operator yields a value of 1 or true if either operand is true (non-zero) or a value of 0 or false if both operands are false (equal to zero). And the operands needn't be boolean; they can be of any scalar type. (In C the result is of type int; in C++ it's of type bool.) The expression

b == c || b == d

is equivalent to

(b == c) || (b == d)

and yields a true result if b is equal to c or if b is equal to d. But this expression:

b == (c || d)

computes the value of (c || d), and the tests whether b is equal to the result of that subexpression.

A similar possible source of confusion is that

x < y < z

is not equivalent to

(x < y) && (y < z)

Rather, it's equivalent to

(x < y) < z

where the false or true (in C++) or 0 or 1 (in C) result of x < y is compared to the value of z.

Upvotes: 2

user2897690
user2897690

Reputation:

The first expression b == c || b == d will give you true if b is equal to either c or d.

The second expression b == (c || d) will check only if b is either equal to 0 or 1 because the output of c || d is binary.

Consider this code:

#include <iostream>
using namespace std;

int main() {
    int b=10,c=9,d=10;
    cout << (b ==c || b ==d )<<endl;
    cout<< ( b == ( c || d)) <<endl;
    d=11;
    cout << (b ==c || b ==d )<<endl;
    cout<< ( b == ( c || d)) <<endl;
    return 0;
}

The output is

1
0
0
0

Now you can clearly see that both expressions are not same.

Upvotes: 5

Related Questions