I have 2 questions:
This code:
struct employee
{
char name[20];
int married :1;
};
How many does married take in memory?
And if I have multiple bit-sized fields Does it good to put them in the same variable of keep them individual?
like:
struct employee
{
char name[31];
int married :1;
int manager :2;
int children :4;
};
Or
struct employee
{
char name[31];
int flage; /* one bit for married, one for manager, and 4 bits for children */
};
Which one is better in memory usage and why???
When you use
int flagefor storing information regarding married manager and children, it MAY take 2 bytes of memory for one object, and every time you have to access a particular information you have to perform bitwise operations on theflagevariable. This will thus require some processing.By using a bitfield, like
int married:1;(you better useunsigned int), that means it MAY take just 1 byte of memory, therefore you MAY save memory (supposing your struct is not padded). As a bonus, you can access its bits directly.So it should be better approach regarding memory and processing.