polmonroig
polmonroig

Reputation: 1017

Empty list iterators comparison is always true

I am testing the list iterators of an empty list with the following code:

Code

#include <iostream>
#include <list>


int main(){
    std::list<int> l;
    bool a, b, c;
    std::list<int>::iterator i = l.begin();
    a = i == --l.end();
    b = ++i == l.end();
    c = ++i == l.end();
    std::cout << a << std::endl;
    std::cout << b << std::endl;
    std::cout << c << std::endl;
}

Result

1
1
1

The result for the three bools is always true, but I am increasing and decreasing the iterators, why do they point to the same address always

Upvotes: 2

Views: 64

Answers (1)

Baum mit Augen
Baum mit Augen

Reputation: 50053

This is just Undefined Behavior because you are not allowed to increment or decrement iterators in a way that makes them go outside the underlying range.

As the range is empty in this case, all three of your operations are illegal and incorrect.

Upvotes: 6

Related Questions