warning: zero as null pointer constant while comparing iterators

Viewed 910

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?

2 Answers

I just wrote a bug in my code?

No, there is no bug in your code.

Is this a false-positive warning

Probably yes. It may be a true-positive for the implementation of the standard library function that you implicitly use, although if that is the case then the warning message is incomplete as it fails to show the code where 0 is used.

It should be a bug also because warnings shouldn't be shown from standard library headers.

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.

Related