I was wondering if there is a clean way of counting from 0 to 255 using an 8 bit datatype, something like:
for(uint8_t i(0);i<=255;++i)
{
....
}
This obviously will not work but it makes it clear you want to count from 0 to 255.
A working solution would be something like:
uint8_t i(0);
do
{
...
++i;
}
while(i > 0);
But here it is not at all clear it counts from 0 to 255.
This will also work but it is just ugly IMHO:
uint8_t i(0);
while(true)
{
...
if (i == 255)
{
break;
}
++i;
}
So I was wondering, is there a clean way of doing this without using a larger datatype?
EDIT:
- I like the version using for because it makes its intend clear without thinking: looping from 0 to 255. All other versions require some thought about what is going on and therefore more likely to confuse others.
- I do not want to use int because the code is for a 8-bit microcontroller with not much memory.
uint8_t i(0);
is a syntax error in C – pmg Nov 10 '09 at 13:06i >= 256
. Sincei
is an 8-bit datatype, it can only hold 0..255. Ifi == 255
and you doi++
it will overflow and theni == 0
and the for loop never exists. In this casei
can never hold 256 which is needed to exit the loop. – rve Feb 11 '12 at 17:01i
still can not hold values above 255. You probably could manually do something likeint t(i), t++, t<=255
but it is not making the code any clearer and you are using more memory. If there was enough memory I would just useint
instead ofuint8_t
– rve Feb 12 '12 at 9:21