Datesfat Chicks
5/15/2011 2:58:00 PM
On Sat, 14 May 2011 14:05:43 -0700 (PDT), "dr.oktopus"
<blindwilly@freeonline.zzn.com> wrote:
>Hi,
>I am developing a little library and I would like to develop it so
>that it will be conforming both to the old and the new (c99) standard.
>I have a function returning a boolean value, so I think that something
>like:
>
>file.h:
>
>#if __STDC_VERSION__ >= 199901L
>#include <stdbool.h>
>#else
>#define bool int
>#endif
>
>/* rest of the header */
>
>bool my_func (void);
>
>file.c:
>
>#if __STDC_VERSION__ >= 199901L
>#define false 0
>#define true (!false)
>#endif
>
>should be. But bool could be defined even in user code.
>What's the proper way to handle this kind of things?
I do embedded work with small micros (2K of RAM is a high-end part for
me), so every bit has to count.
I typically use _Bool_ or _Boolean_ (forget what the right keyword
is). Anyway, that does a few neat things in the development tools:
a)It causes the linker to manage RAM at the bit level (rather than the
byte level). So you can link a bunch of modules together each with
_Bool_'s, and variables from different modules are actually often in
the same byte. No RAM wasted! The tools pack the bits.
b)The little microcontrollers typically have instructions to set,
clear, and test bits of RAM economically, so it is pretty efficient.
It is rare to find a micro where something like this is requied:
ld a, whatever
or a, #64
ld whatever, a
Most little micros can do that in one instruction--a RMW sequence such
as I demonstrated above is rare.
All that being said ...
I really don't see a compelling need for Boolean variables in most
programs written for larger machines, except in the cases where there
are arrays of them and it would be a huge RAM waste (and then you'd
want to have an array of integers and mask bits in and out).
In most cases with larger machines, an "int" is just fine as a
Boolean. Wasting 31 or 63 bits is a non-issue.
The only thing I'd caution you to do is that if you're going to agree
that a variable is Boolean, it has two equivalence classes:
a)0 = FALSE
b)Everything else is TRUE.
So, don't do this in the code:
if (variable == TRUE)
If you do that, then there are a large number of values that are
neither TRUE nor FALSE.
Use "(variable)" and "(!variable)" instead.
And of course use || and &&.
I just don't see a need for _Bool_ in most large programs.
"int" is just fine.
DFC