Why the infinite loop when data type is unsigned int?

后端 未结 3 1456
萌比男神i
萌比男神i 2020-12-12 05:42

The below code runs perfectly.Gives the correct output but, the moment I change the sign of the variables from signed to unsigned the program runs into an infinite loop. The

相关标签:
3条回答
  • 2020-12-12 06:08

    As other answers already noted, the loop

    for(i=count-1;i>=0;--i)
    

    is an infinite loop if i is unsigned. It can be rewritten in a different form as

    for (i = count - 1; i != -1; --i)
    

    which will work as intended for both signed and unsigned i. However, some might find it less readable than the original.

    0 讨论(0)
  • 2020-12-12 06:19

    An unsigned int can never be negative, so i >= 0 holds true all the time, that means that a loop like

    unsigned int value;
    
    value = 10;
    while (value-- >= 0) {}
    

    is effectively an inifinte loop, as well as your for (i = count - 1 ; i >= 0 ; --i) is.

    Compilers do warn about this, so if you compile your code passing the right flags to the compiler, it should tell you that the condition will be always true.

    You should note that while the >= makes no difference in this respect,

    unsigned int value;
    
    value = 10;
    while (value-- != 0) {}
    

    does work, as while (value-- > 0) also does, because value can be 0, but it can't be < 0.

    There is also, no unsigned int integer overflow, so the loop will be infinite without causing undefined behavior, this answer has an explanation of what happens when you add 1 to the maximum value, if you subtract one from the minimum value, then I am sure you can "guess" what would happen from the same answer.

    0 讨论(0)
  • 2020-12-12 06:25

    The problem is that,

    for(i=count-1;i>=0;--i)
    

    Will never exit if i is unsigned. Because i is unsigned it will always be greater than or equal to zero, and thus the loop can't end.

    0 讨论(0)
提交回复
热议问题