On the question 'why do we need to use bit-fields', searching on Google I found that bit fields are used for flags. Now I am curious,
Way of defining bit field from the book:
struct { unsigned int is_keyword : 1; unsigned int is_extern : 1; unsigned int is_static : 1; } flags;
I am confused why we are using int
, but not short
or something smaller than an int
.
Bit fields can be used to reduce memory consumption when a program requires a number of integer variables which always will have low values. For example, in many systems storing an integer value requires two bytes (16-bits) of memory; sometimes the values to be stored actually need only one or two bits.
Bit-fields and unions may be combined in a way that permits programmers to pack and unpack bits in an integer. Unions allow programmers to circumvent C++'s strong typing rules while bit-fields allow programmers to access the bits that encode the compressed information.
No, you can't. Bit field can only be used with integral type variables.
A quite good resource is Bit Fields in C.
The basic reason is to reduce the size used. For example if your write:
struct { unsigned int is_keyword; unsigned int is_extern; unsigned int is_static; } flags;
You will use at least 3 * sizeof(unsigned int)
or 12 bytes to represent 3 little flags, that should only need 3 bits.
So if you write:
struct { unsigned int is_keyword : 1; unsigned int is_extern : 1; unsigned int is_static : 1; } flags;
This uses up the same space as one unsigned int
, so 4 bytes. You can throw 32 one bit fields into the struct before it needs more space.
This is sort of equivalent to the classical home brew bit field:
#define IS_KEYWORD 0x01 #define IS_EXTERN 0x02 #define IS_STATIC 0x04 unsigned int flags;
But the bit field syntax is cleaner, compare:
if (flags.is_keyword)
against:
if (flags & IS_KEYWORD)
and obviously less error prone.
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