jeudi 2 mars 2017

Value of integer bit field is alternately equal to 0 or 1 when bit field width is less than the needed

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 or an undefined behavior. 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

Aucun commentaire:

Enregistrer un commentaire