简体   繁体   中英

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.

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.

This is because int type overflow. See the type limits . For such a huge number comparison you should use long instead int

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM