| 1 |
.. title:: clang-tidy - readability-string-compare |
| 2 |
|
| 3 |
readability-string-compare |
| 4 |
========================== |
| 5 |
|
| 6 |
Finds string comparisons using the compare method. |
| 7 |
|
| 8 |
A common mistake is to use the string's ``compare`` method instead of using the |
| 9 |
equality or inequality operators. The compare method is intended for sorting |
| 10 |
functions and thus returns a negative number, a positive number or |
| 11 |
zero depending on the lexicographical relationship between the strings compared. |
| 12 |
If an equality or inequality check can suffice, that is recommended. This is |
| 13 |
recommended to avoid the risk of incorrect interpretation of the return value |
| 14 |
and to simplify the code. The string equality and inequality operators can |
| 15 |
also be faster than the ``compare`` method due to early termination. |
| 16 |
|
| 17 |
Examples: |
| 18 |
|
| 19 |
.. code-block:: c++ |
| 20 |
|
| 21 |
std::string str1{"a"}; |
| 22 |
std::string str2{"b"}; |
| 23 |
|
| 24 |
// use str1 != str2 instead. |
| 25 |
if (str1.compare(str2)) { |
| 26 |
} |
| 27 |
|
| 28 |
// use str1 == str2 instead. |
| 29 |
if (!str1.compare(str2)) { |
| 30 |
} |
| 31 |
|
| 32 |
// use str1 == str2 instead. |
| 33 |
if (str1.compare(str2) == 0) { |
| 34 |
} |
| 35 |
|
| 36 |
// use str1 != str2 instead. |
| 37 |
if (str1.compare(str2) != 0) { |
| 38 |
} |
| 39 |
|
| 40 |
// use str1 == str2 instead. |
| 41 |
if (0 == str1.compare(str2)) { |
| 42 |
} |
| 43 |
|
| 44 |
// use str1 != str2 instead. |
| 45 |
if (0 != str1.compare(str2)) { |
| 46 |
} |
| 47 |
|
| 48 |
// Use str1 == "foo" instead. |
| 49 |
if (str1.compare("foo") == 0) { |
| 50 |
} |
| 51 |
|
| 52 |
The above code examples show the list of if-statements that this check will |
| 53 |
give a warning for. All of them uses ``compare`` to check if equality or |
| 54 |
inequality of two strings instead of using the correct operators. |