Brian Deragon Brian Deragon - 3 months ago 17
C++ Question

c++ unsigned infinite loop comparison bug

#include <iostream>


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:

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


I tried using:

#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.

Answer

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.