Search code examples
c++for-loopunsigned-integer

unsigned int causes infinite for-loop


There are two loops below. The first one works well while the second one is an infinite loop. Why?

for (unsigned int i=0; i<3; ++i)
{
    std::cout << "i= " << i << std::endl; // this gives proper result
}

for (unsigned int i=3; i>=0; --i)
{
    std::cout << "i= " << i << std::endl; // infinite loop
}

Solution

  • An unsigned int can never be less than 0. That's what makes it unsigned. If you turn on some warning flags, your compiler should tell you about your problem: i >= 0 is always true for an unsigned value.

    Clang, for example, required no special flags at all to warn:

    example.cpp:5:29: warning: comparison of unsigned expression >= 0 is always true
          [-Wtautological-compare]
        for (unsigned int i=3; i>=0; --i)
                               ~^ ~
    1 warning generated.
    

    GCC required -Wextra:

    example.cpp: In function ‘int main()’:
    example.cpp:5: warning: comparison of unsigned expression >= 0 is always true