Search code examples
c++iteratorclangcompiler-warningsclang-tidy

warning: zero as null pointer constant while comparing iterators


For a code segment as below: (or check https://godbolt.org/z/15bqMj)

std::vector<int> v{1,2,1,2,1,2};
for (auto it = v.cbegin(); (it = find_if(it, v.cend(), somePredicate)) < v.cend(); ++it) {
    std::cout << *it << std::endl;
}

I got warnings from the compiler (clang 11 with -std=c++20 -Wzero-as-null-pointer-constant):

warning: zero as null pointer constant [clang-diagnostic-zero-as-null-pointer-constant]
  for (auto it = v.cbegin(); (it = find_if(it, v.cend(), somePredicate)) < v.cend(); ++it) {
                                                                         ^
/usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/bits/stl_iterator.h:1080:5: note: while rewriting comparison as call to 'operator<=>' declared here
    operator<=>(const __normal_iterator<_IteratorL, _Container>& __lhs,
    ^
note: this fix will not be applied because it overlaps with another fix
warning: use nullptr [hicpp-use-nullptr,modernize-use-nullptr]
  for (auto it = v.cbegin(); (it = find_if(it, v.cend(), somePredicate)) < v.cend(); ++it) {
                                                                         ^
note: this fix will not be applied because it overlaps with another fix
warning: zero as null pointer constant [-Wzero-as-null-pointer-constant]
  for (auto it = v.cbegin(); (it = find_if(it, v.cend(), somePredicate)) < v.cend(); ++it) {
                                                                         ^
                                                                         nullptr
/usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/bits/stl_iterator.h:1080:5: note: while rewriting comparison as call to 'operator<=>' declared here
    operator<=>(const __normal_iterator<_IteratorL, _Container>& __lhs,
    ^

Is this a false-positive warning, or I just wrote a bug in my code?


Solution

  • Usually iterators are compared only using == and !=. As far as I know other comparison operators are not defined for iterators.

    It looks like clang tries to use <=> operator for your < and because of it internal implementation gives your this warning.

    Edit: Random Access iterators should define all comparison operators and since vector should return random access iterator it seems there is bug in clang.