What is an elegant way of executing something similar to this without entering an infinite loop, if i
must be an unsigned char
?
for (unsigned char i = 0; i < 256; ++i) {
printf("%d\n", i);
}
Infinite time "hello" print because reason is simple, unsigned char have a limit up to 255 after that if u again increment on it ,they will become zero & again they reach to 255 then zero , so variable i never reach 1000 we call it infinite loop.
The maximum value for an unsigned char is 255, or rather 0XFF or 11111111. When you go 1 above it, it becomes 00000000. Now, for every increment it starts from 0. Hence 0XFF + 5 is going to be 4, basically.
unsigned is a qualifier which is used to increase the values to be written in the memory blocks. For example - char can store values between -128 to +127, while an unsigned char can store value from 0 to 255 only. unsigned store only positive values, its range starts from 0 to (MAX_VALUE*2)+1.
The basic ASCII values are in range 0 to 127. The rest part of the ASCII is known as extended ASCII. Using char or signed char we cannot store the extended ASCII values. By using the unsigned char, we can store the extended part as its range is 0 to 255.
unsigned char i = 0;
do {
printf("%u\n",i);
}while(++i != 0);
Do the increment in the loop test and test against the wrapped value.
As a general rule of thumb: if your iterator variable needs to hold all values between 0 and "Uxxx_MAX", you picked a too narrow type for the algorithm.
You should have considered using uint16_t
instead.
There are just so many cases where you can't use a large int type instead of your unsigned char. So let me ask you, is your application a real time embedded system, written for an 8-bit MCU, where you have found that this very loop is a performance bottleneck?
uint8_t
as the type of the iterator, and comment why you did it. uint16_t
or a larger integer type.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With