I am testing a code in C where i intentionally define an integer bit field(variable not_enough) inside a struct to width 1 but assign values which require 2 or 3 bits. It is important to note that i get the values from an enum. After this, i print the values. I would expect to either get default value of integer equal to 0. But what i get is value alternately equal to 0 or 1.
Can you please explain why?
Here is the code below:
#include <stdio.h>
typedef enum {
FIRST = 9,
SECOND = 8,
THIRD = 7,
FOURTH = 6,
FIFTH = 5,
SIXTH = 4,
SEVENTH = 3,
EIGHTH = 2
} directionValues;
struct {
unsigned int enough : 3;
unsigned int not_enough: 1; //intentionally limited to 1 bit
} test_bit;
int main(void) {
test_bit.enough = EIGHTH;
printf("Enough bits for variable. Value is %d\n",test_bit.enough);
test_bit.not_enough = THIRD;
printf("Not enough bits for variable. Value is %d\n",test_bit.not_enough);
test_bit.not_enough = FOURTH;
printf("Not enough bits for variable. Value is %d\n",test_bit.not_enough);
test_bit.not_enough = FIFTH;
printf("Not enough bits for variable. Value is %d\n",test_bit.not_enough);
test_bit.not_enough = SIXTH;
printf("Not enough bits for variable. Value is %d\n",test_bit.not_enough);
test_bit.not_enough = SEVENTH;
printf("Not enough bits for variable. Value is %d\n",test_bit.not_enough);
test_bit.not_enough = EIGHTH;
printf("Not enough bits for variable. Value is %d\n",test_bit.not_enough);
return 0;
}
Output is:
Enough bits for variable. Value is 2
Not enough bits for variable. Value is 1
Not enough bits for variable. Value is 0
Not enough bits for variable. Value is 1
Not enough bits for variable. Value is 0
Not enough bits for variable. Value is 1
Not enough bits for variable. Value is 0
Thats because only last bit is set to your variable because it has 1 bit allowed only.
You are actually doing this:
test_bit.not_enough = 7; //(0111) Bit 0 is 1
printf("Not enough bits for variable. Value is %d\n",test_bit.not_enough);
test_bit.not_enough = 6; //(0110) Bit 0 is 0
printf("Not enough bits for variable. Value is %d\n",test_bit.not_enough);
test_bit.not_enough = 5; //(0101) Bit 0 is 1
printf("Not enough bits for variable. Value is %d\n",test_bit.not_enough);
test_bit.not_enough = 4; //(0100) Bit 0 is 0
printf("Not enough bits for variable. Value is %d\n",test_bit.not_enough);
test_bit.not_enough = 3; //(0011) Bit 0 is 1
printf("Not enough bits for variable. Value is %d\n",test_bit.not_enough);
test_bit.not_enough = 2; //(0010) Bit 0 is 0
printf("Not enough bits for variable. Value is %d\n",test_bit.not_enough);
Since you have only 1 bit available memory, only first bit (LSB) is set to your variable.