- [Instructor] Bit Fields provide the ability
to pack multiple values
into less space than they would normally take.
This is bitfields.cpp
from chapter three of the exercise files.
And you notice that I have here a structure
and for each of these elements
I have a colon and a number, and that's the number
of bits that will be used for that element.
And so for these Boolean elements
they're just going to take up one bit.
And so the compiler can take all four
of these and it can put them in one Boolean variable.
And then I have an unsigned int, which is four bits.
So theoretically, the compiler, if it's smart, can take all
of this and put it in the space of one integer.
And you see that it's used
just like you would use a structure.
When I build this and run it,
you see, I get this result.
I'm testing these Booleans.
If Homer likes music, then it prints, likes music.
He does not have hair.
So it doesn't print that.
And he does not have a dinosaur.
So it doesn't print that.
And he has three children.
So this makes something like a preferences structure.
It makes it pretty convenient.
You'll notice that I'm testing
both the structure and the size of an int.
So I can see that it's taking
up the size of an integer on this machine.
Be aware that the language doesn't guarantee
any particular bit packing
or any particular bit ordering.
So how your data is actually stored
in memory is highly dependent upon the target architecture.
So while it takes up 32 bits on this Mac
it may take more or less space on your machine
depending on how it aligns values and memory and like that.
So on a PC using Microsoft Visual C++,
this structure actually took up 64 bits
even though an int is 32 bits on a PC.
So this becomes an issue
if you store your pack data in a file
and then expect to read it on a different machine.
It's also worth noting that bitfields can be a source
of trouble in concurrent or threaded programming
because each of these individual values is not
actually an atomic value on its own.
And all the bits in a unit have to be read
and written at the same time.
So Bit Fields can be useful in situations
where an object may have many small properties
like this example of a preferences structure.