C++ reverse 'for' loop

Let the compiler tell you what's wrong!

If you compiled your program with warnings enabled, the compiler would tell you something like this:

<source>: In function 'int main()':

7:43: warning: comparison of unsigned expression in '>= 0' is always true [-Wtype-limits]
    7 |     for(std::size_t i = vec.size() - 1; i >= 0; --i) {
      |                                         ~~^~~~

Why is that? It's because std::size_t is an unsigned type in C++; it only represents non-negative numbers. Read more about turning on warnings and why it's important: Why should I always enable compiler warnings?

So, how should we reverse-iterate?

I've decided to split my answer here off to a separate question, independent of OP's bug. Please go read it.


The problem is that size_t is an unsigned integer, i.e. it can only have positive values. When you decrease 0 for an unsigned type an underflow happens and the result is usually the largest integer representable by that type, e.g. 18446744073709223794 in your case. Finally the check for i >= 0 is always true for any unsigned type and your loop will never terminate.