struct stats
{
char top : 1;
char bottom : 1;
char side : 2;
} MyStat;
I have seen this format with integers but how does the above char bit field work and what does it represent?
Thank You.
struct stats
{
char top : 1;
char bottom : 1;
char side : 2;
} MyStat;
I have seen this format with integers but how does the above char bit field work and what does it represent?
Thank You.
it just defines the size of the variable that you will use.
This is not supported by the standard (typical use is unsigned int), but it's a nice attempt :)
re: your query, it's an attempt by the implementer to use less memory for their bitfields (char as opposed to unsigned int)
Additionally, from Atmel, we get:
Char bit fields work in the same way as int, just the base type is 8-bit wide, not 32-bit. So you'd get a struct stats, which has the size of 1 byte, and 3 member variables, occupying a total of 4 bits.
Bitfields should be declared with type
signed int
,unsigned int
, orbool
from<stdbool.h>
. Other types may or may not be legal (depending on the platform), but be careful about the signedness — plainint
may be taken to be unsigned for a bitfield.That said, it may be a hint to the compiler that the alignment of the
struct
should be 1 and notsizeof(int)
. And the compiler is allowed to acceptchar
and assign it such meaning.According to C99 6.7.2.1/9,
and a footnote: