Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Inequality operator (!=)

The != operator tests whether its operands are unequal. The built-in operation returns bool after required conversions. Classes can define operator!= or use an eligible operator== through comparison rewriting rules.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

lhs != rhs

The expression lhs != rhs tests inequality. The built-in operator returns true for unequal operands and false for equal operands; its result has type bool. Arithmetic operands undergo the usual arithmetic conversions, so the comparison concerns the converted values.

Comparing pointers does not compare the contents of the pointed-to objects. Operators == and != group left-to-right: a != b != c means (a != b) != c, not a test that all three values are pairwise different.

For classes, an overloaded operator!= can define custom behavior. In C++23, overload resolution can also select an eligible operator== and negate its result; this path requires a possibly cv-qualified bool result. This does not generate a separate operator!= function.

The example uses this rule for Item: the defaulted operator== compares id. This entry targets C++23; the supplied site hosts an evolving draft rather than a frozen C++23 text.

Examples

#include <iostream>

struct Item {
    int id;
    bool operator==(const Item&) const = default;
};

int main() {
    const Item a{3};
    const Item b{5};
    std::cout << std::boolalpha;
    std::cout << (3 != 5) << '\n';
    std::cout << (3 != 3) << '\n';
    std::cout << (a != b) << '\n';
}

Result

true
false
true

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources