Yoshi said:
First I tried bool, but it didn't work(now I see it's _Bool). Then I
tried unsigned short, and it worked for gcc on Linux. I thought it
would be better since unsigned short would only consume 2 bytes, but
int would be 4 bytes(not good thing to do though..)
Prior to C99, C didn't have a boolean type. A lot of code defined its
own type, often using the name "bool", so when the C99 committee
decided to add a boolean type, they couldn't make "bool" a keyword
without breaking existing code. So they introduced the keyword
"_Bool", but they also created the new <stdbool.h> header which
defines "bool" as an alias for "_Bool". (This doesn't break existing
code, since no existing code would have "#include <stdbool.h>".)
But note that both _Bool and bool are C99-specific, and some compilers
might not support it.
In any case, a bit field declared as
some_type bf:1;
will only occupy 1 bit, whatever some_type is. That's the whole
point.
If I wanted a 1-bit bit field, I'd use unsigned int:
unsigned int bf:1;
(A plain int bit field can be either signed or unsigned; that's an
annoyingly odd historical glitch in the language.)
I usually try and error when I code, but could you tell me where
should I refer to write a portable code? I cannot see which standard
document I should check because it looks so many standards exist.
The current official standard for the C language consist of the 1999
ISO C standard plus the three Technical Corrigenda. They've been
conveniently merged into a not-quite-but-almost-official document,
<
http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf>.
Support for the C99 standard is not yet universal. The C90 standard
is still in wide use. I don't know of a good free source for it.
Note that the standard documents are quite dense; they're definitely
not tutorials. A good tutorial, arguably the best, is "The C
Programming Language", 2nd Edition, by Kernighan & Ritchie (K&R2). It
covers C90, not C99, but that's not much of a problem. A good
reference book is "C: A Reference Manual", 5th Edition, by Harbison &
Steele (H&S5). The comp.lang.c FAQ, <
http://www.c-faq.com/>, is
another excellent resource; it also includes a section on other
resources, including some books that I've neglected to mention here.
[...]
OK, thanks for telling me that, though I want to see the reference...
Any decent reference should explain how bit fields are defined. The
real point here, though, is the *lack* of any reference specifying how
bit fields are laid out (though you might find documents that describe
how they're handled by a particular compiler).