Equality Operators: == and !=
The latest version of this topic can be found at Equality Operators: == and !=.
Syntax
expression == expression
expression != expression
The binary equality operators compare their operands for strict equality or inequality.
The equality operators, equal to (==
) and not equal to (!=
), have lower precedence than the relational operators, but they behave similarly. The result type for these operators is bool
.
The equal-to operator (==
) returns true (1) if both operands have the same value; otherwise, it returns false (0). The not-equal-to operator (!=
) returns true if the operands do not have the same value; otherwise, it returns false.
The not_eq
operator is the text equivalent of !=
. There are two ways to access the not_eq
operator in your programs: include the header file iso646.h
, or compile with the /Za (Disable language extensions) compiler option.
// expre_Equality_Operators.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;
int main() {
cout << boolalpha
<< "The true expression 3 != 2 yields: "
<< (3 != 2) << endl
<< "The false expression 20 == 10 yields: "
<< (20 == 10) << endl;
}
Equality operators can compare pointers to members of the same type. In such a comparison, pointer-to-member conversions, as discussed in Pointer-to-Member Conversions are performed. Pointers to members can also be compared to a constant expression that evaluates to 0.
Expressions with Binary Operators
C++ Operators
C++ Built-in Operators, Precedence and Associativity
C Relational and Equality Operators