Issue 178731
Summary [clang-tidy] New check: bugprone-missing-end-comparison
Labels clang-tidy
Assignees
Reporter denzor200
    A common error in C++ code is using the return value of algorithms like `std::find`, `std::search`, `std::lower_bound`, etc., directly in boolean contexts without comparing against the end iterator. While this is a compilation error for most STL iterators, it can compile silently for raw pointers and custom iterators with `operator bool()`, leading to severe logical bugs.

**Examples of problematic code:**

```cpp
int arr[] = {1, 2, 3};
int* begin = arr;
int* end = arr + 3;

// BUG: Always evaluates to true (unless nullptr is returned)
if (std::find(begin, end, 55)) {  // Should be: != end
    std::cout << "found\n";
}

// Same issue with algorithms returning iterators
auto it = std::lower_bound(begin, end, 2);
if (it) {  // Should be: != end
    // ...
}
```

**Proposed Solution:**
Create a check that detects all instances where:
1. A standard algorithm returns an iterator (e.g., `std::find`, `std::search`, `std::partition_point`)
2. The return value is used directly in a boolean context
3. The return value is not explicitly compared with an end iterator

**Algorithms to check (non-exhaustive):**
- `std::find`, `std::find_if`, `std::find_if_not`
- `std::search`, `std::search_n`
- `std::lower_bound`, `std::upper_bound`, `std::equal_range`
- `std::partition_point`
- `std::min_element`, `std::max_element`
- `std::adjacent_find`
- `std::mismatch` (first return value)

In C++20 mode this check should also handle range-based calls.

**Example Fix:**
```diff
- if (std::find(v.begin(), v.end(), value)) {
+ if (std::find(v.begin(), v.end(), value) != v.end()) {
```
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to