I have some code here that uses bitsets to store many 1 bit values into a char.
Basically
struct BITS_8 {
char _1:1;
(...)
char _8:1;
}
Now i was trying to pass one of these bits as a parameter into a function
void func(char bit){
if(bit){
// do something
}else{
// do something else
}
}
// and the call was
struct BITS_8 bits;
// all bits were set to 0 before
bits._7 = 1;
bits._8 = 0;
func(bits._8);
The solution was to single the bit out when calling the function:
func(bits._8 & 0x80);
But i kept going into //do something because other bits were set. I was wondering if this is the correct behaviour or if my compiler is broken. The compiler is an embedded compiler that produces code for freescale ASICs.
EDIT: 2 mistakes: the passing of the parameter and that bits._8 should have been 0 or else the error would make no sense.
Clarification
I am interested in what the standard has to say about the assignment
struct X{
unsigned int k:6;
unsigned int y:1;
unsigned int z:1;
}
X x;
x.k = 0;
x.y = 1;
x.z = 0;
char t = X.y;
Should now t contain 1 or b00000010?
Ok, it was a compiler bug. I wrote the people that produce the compiler and they confirmed it. It only happens if you have a bitfield with an inline function.
Their recommended solution is (if i don’t want to wait for a patch)
The other answers are right about the correct behaviour. Still i’m marking this one as the answer as it is the answer to my problem.