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

后端 未结 4 759
执笔经年
执笔经年 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:03

    If you really need to use unsigned char then you can use

    unsigned char i = 0;
    do {
        // ... 
    } while(++i);
    

    When an arithmetic operation on an unsigned integer breaks its limits, the behaviour is well defined. So this solution will process 256 values (for 8-bit unsigned char).

提交回复
热议问题