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:
What about:
uint8_t i = 0;
do {
...
} while (i++ != 255);
I'm not sure what you mean but
uint8_t i = 0;
do {
...
} while (++i & 255) ;
should do what you ask and has an explicit reference to 255 (useless if your compiler is C99 standard and uint8_t is really 8 bits).
What's wrong with the obvious?
i = 255;
do {
work();
} while (i--);
You seem to want to convey the message of counting from 0 to 255 by the data type you are using, but what's the significance of 255? You should probably #define this magic number with a name explicitly stating the purpose of it. Also, a comment above the statement would be way more helpful than trying to "encode" all that information in somewhat weird looking statements.
For example:
#define MAX_RETRIES 255
unsigned int retries;
for(retries = 0; retries <= MAX_RETRIES; ++retries)
{
do_retry_work();
}
If needed, add a comment, why the number of retries is limited to 255.
I would suggest that the simple solution:
for (int i = 0; i < 256; ++i) {
...
}
is probably also going to be the most efficient solution.
Even if you use a smaller (1-byte) data type. The C compiler will promote it to an int in any expression.
On an 8-bit controller an int is probably 16-bits. Using a single-byte type will only save one byte of stack space. Then again the compiler may put that variable in a register, so there will not be any space savings anyway.
Check the assembly code generated by the above code, then decide whether or not it needs (space) optimization.
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