Search code examples
c++unsigned-integer

c++ unsigned infinite loop comparison bug


Noticed a bug in one of the programs I was working on, extracted the code, and it's basically this.
It does an unsigned comparison to a signed int and results in an infinite loop:

#include <iostream>  

int main()
{
    unsigned int i = 0;
    while (i < 1000000)
    {
        printf("%o\n", i);
        ++i;
    }
    return 0;
}

I tried using this instead:

#include <iostream>

int main()
{
    unsigned int i = 0;
    while (i < 1000000u)
    {
        printf("%o\n", i);
        ++i;
    }
    return 0;
}

Which I thought would fix the signed/unsigned comparison, and it doesn't, it's still hitting an infinite loop. So I also tried casting it to unsigned int, and no dice, still infinite loops.

Using Visual Studio 2015, full optimization, release compiler.


Solution

  • While I can not reproduce the infinite loop on Win7 nor Ubuntu (both 64-bit) I believe the problem is your printf() function with unsigned octal number representation which leads you to think it enters an infinite loop. Changing the %o parameter to %u might clarify the issue.