C & C++

C & C++

Made by DeepSource

Using std::string::compare over equality operators CXX-C2017

Anti-pattern
Minor

Found using equality string comparison method std::string::compare instead of using == which makes the code less readable.

A common mistake is to use the string's compare method instead of using the equality or inequality operators. The compare method is intended for sorting functions and thus returns a negative number, a positive number, or zero depending on the lexicographical relationship between the strings compared. If an equality or inequality check can suffice, that is recommended.

This is recommended to avoid the risk of incorrect interpretation of the return value and to simplify the code. The string equality and inequality operators can also be faster than the compare method due to early termination.

Bad Practice

std::string str1{"a"};
std::string str2{"b"};

if (str1.compare(str2)) {
    // code..
}

if (!str1.compare(str2)) {
    // code..
}

if (str1.compare(str2) == 0) {
    // code..
}

The above code examples show the list of if-statements that this check will give a warning for. All of them use compare to check the equality or inequality of two strings instead of using the correct operators.

Recommended

std::string str1{"a"};
std::string str2{"b"};

if (str1 != str2) {
    // code ..
}

if (str1 == str2) {
    // code ..
}

if (str1 == str2) {
    // code ..
}

By using the correct equality and inequality operators, the code becomes more readable and less prone to misinterpretation.