for (unsigned char i = 0; i<=0xff; i++) produces infinite loop

后端 未结 4 769
执笔经年
执笔经年 2020-12-21 04:25

Why does the following c code end up in an infinite loop?

for(unsigned char i = 0; i <= 0xff; i++){}

It is the same result with:

4条回答
  •  孤城傲影
    2020-12-21 05:13

    Because you wraparound. An unsigned char values range between 0-255, and because unsigned arithmetic are well defind, you actually wrap the value of i to 0 and the condition is still met and the iteration continues ad infinitum.

    In the case of signed values, it is an undefined behaviour and value stored in i might not be 0. But still it will be smaller than the maximum value you could store in a char and the condition is still met.

提交回复
热议问题