Re: My idea of fully-portable C code
- From: Hans-Bernhard Bröker <HBBroeker@xxxxxxxxxxx>
- Date: Tue, 13 May 2008 20:59:31 +0200
Tomás Ó hÉilidhe wrote:
To use the least
amount of memory possible for each LED, I thought I'd go with the
following strategy:
* Use three bits per LED. 00 = Off. 01 = Red. 10 = Unused. 11 =
Green.
The reasoning behind that choice of encoding is flawed. Putting an unused state in the middle of a list of values will "use the least amount of memory possible" only by luck, but never by design.
void SetChunk(uint_fast16_t const i, uint_fast8_t const state);
Here's your first unwarranted assumption (although it's not one of portability). You've validated your self-stated requirement:
(Of course you can set the chunk size bigger or smaller than 3 bits)
Using uint8_fast_t for the datatype disallows setting the chunk size to more than 8 bits.
In addition to that, 'i' should really be size_t or something at least as large as that. As-is, you introduce yet another hardcoded limitation.
#define TOTAL_BITS_NEEDED (QUANTITY_CHUNKS * BITS_PER_CHUNK)
Bad macro. Parentheses missing around QUANTITY_CHUNKS and BITS_PER_CHUNK leave the code vulnerable to funny definitions of those constants (e.g. #define BITS_PER_CHUNK 2+3) The same problem occurs repeatedly later on.
And it has a portability problem, too! Check out what this does for QUANTITY_CHUNKS=60000u, BITS_PER_CHUNK=6u, on a 16-bit host platform. You lose. Thanks for playing.
#define BITS_ALL_ONES(x) ((1u << (x)) - 1u)
Will fail as soon as pow(2,x) > (UINT_MAX + 1)... (e.g. x=17 on a 16-bit platform).
#define CHUNK_ALL_ONES (BITS_ALL_ONES(BITS_PER_CHUNK))
.... so this fails if I set BITS_PER_CHUNK to more than the number of bits in an unsigned int (after lifting the earlier restriction about uint8_fast_t).
I've written this post to show an example of fully-portable code, that
is, code that will behave exactly as intended on every conceivable
implementation of the C89 standard.
Well, it doesn't fulfill that promise. And that not just on some conceivable implementation of the C89 standard, but actually on entire *class* of systems that are in wide-spread usage.
.
- Follow-Ups:
- Re: My idea of fully-portable C code
- From: Andrew Smallshaw
- Re: My idea of fully-portable C code
- From: Tomás Ó hÉilidhe
- Re: My idea of fully-portable C code
- References:
- My idea of fully-portable C code
- From: Tomás Ó hÉilidhe
- My idea of fully-portable C code
- Prev by Date: Re: Best way to get 2.5 volts from somewhere? (Vcc = 5 volts)
- Next by Date: Re: Best way to get 2.5 volts from somewhere? (Vcc = 5 volts)
- Previous by thread: Re: My idea of fully-portable C code
- Next by thread: Re: My idea of fully-portable C code
- Index(es):
Relevant Pages
|