C & C++

C & C++

Made by DeepSource

Incorrect use of strcmp CXX-W2050

Bug risk
Major

Suspicious usage of runtime string comparison functions can lead to unintended behavior and bugs in C and C++ code. This check detects calls to string comparison functions, such as strcmp, where the result is implicitly compared to zero. It is recommended to explicitly compare the result to a valid constant value, such as < 0, > 0, or == 0, to ensure the desired behavior.

A common mistake is to compare the result to 1 or -1, which is incorrect usage of the returned value. Instead, the result should be compared to 0 for equality.

Additionally, this check warns if the result value is implicitly cast to a non-integer type. This can occur when the returned value is used in an incorrect context. It is important to ensure that the result is used in a context that matches its type.

Bad Practice

if (strcmp(...) == -1) {
    // Incorrect usage of the returned value.
}

if (strcmp(...) < 0.) {
    // Incorrect usage of the returned value.
}

Recommended

// if not zero then not equal
if (strcmp(...) != 0) {
    // Correctly compares the result to a valid constant.
}

// strcmp returns int promoting to float is meaningless
if (strcmp(...) < 0) {
    // Correctly compares the result to a valid constant.
}

References