Reputation: 43
typedef struct{
int a:1, b:1;
}test;
a
and b
are capable to store a number up to 255. If somehow variable a
stores a bigger value than that, this will affect the value of b
,right? I am terrible at memory management. Also, is it recommended to alter the size of a field in a struct this way?
Upvotes: 1
Views: 68
Reputation: 30936
Most variables in C have a size that is an integral number of bytes. Bit-fields are a part of a structure that don't
necessarily occupy a integral number of bytes; they can any number of bits. Multiple bit-fields can be packed into a
single storage unit. Here these are 1 bit bitfiels capable of holding 0
and -1
.
And in case there is a larger number being stored in a 1 bit bitfield then this would be undefined behavior (signed overflow).
More prominently use unsigned
type in bit field in this case
typedef struct{
unsigned int a:1, b:1;
}test;
Upvotes: 1