Summary
|
|
struct |
– structure containing one or multiple fields, each with its own type (or compound type)
– size is combined size of all the fields, padded for byte alignment
– anonymous or named |
union |
– structure containing one of several fields, each with its own type (or compound type)
– size is size of largest field
– anonymous or named |
Bit fields |
– structure fields with width in bits
– aligned and ordered in architecture-dependent manner can result in inefficient code |
|
Assuming a 32-bit x86 processor, evaluate sizeof(struct foo). |
struct foo {
short s;
union {
int i;
char c;
} u;
unsigned int flag_s : 1;
unsigned int flag_u : 2;
unsigned int bar;
}; |
|
|
Q: How can we rearrange the fields to minimize the size of struct foo? |
A: order from largest to smallest. What is the sizeof(struct foo)? |
struct foo {
union {
int i;
char c;
} u;
unsigned int bar;
short s;
unsigned int flag_s : 1;
unsigned int flag_u : 2;
}; |
|
|
|