Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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:

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

In which way do I have to modify the code, to get it working as expected (without using int or unsigned int datatype)?

like image 698
fragwürdig Avatar asked Nov 27 '22 04:11

fragwürdig


1 Answers

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).

like image 199
Weather Vane Avatar answered Jan 31 '23 14:01

Weather Vane