Why the infinite loop when data type is unsigned int?

后端 未结 3 1455
萌比男神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: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.

提交回复
热议问题