Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping with an unsigned char

Tags:

c

loops

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); 
}   
like image 392
rid Avatar asked Oct 30 '12 13:10

rid


People also ask

How many times will this loop execute unsigned char?

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.

Can we increment unsigned char?

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.

How do you use unsigned char?

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.

Why do we need unsigned char?

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.


2 Answers

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.

like image 153
Daniel Fischer Avatar answered Nov 12 '22 11:11

Daniel Fischer


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?

  • If yes, then write an obscure loop with uint8_t as the type of the iterator, and comment why you did it.
  • If no, then use uint16_t or a larger integer type.
like image 34
Lundin Avatar answered Nov 12 '22 12:11

Lundin