Why the infinite loop when data type is unsigned int?

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

提交回复
热议问题