Next-93
Next-93

Reputation: 97

Mysterious behavoiur in bit fields

I have the bit fields like below

union
{
    unsigned int REG;

    struct
    {
        unsigned char toggle : 1;
    } flag;

    struct
    {
        unsigned char field : 3;
        unsigned char count : 3;
    } fields;
} bitfield;

When I toggle the bit bitfield.flag.toggle = !bitfield.flag.toggle every time it is affecting bitfield.fields.field i.e when bitfield.flag.toggle is zero bitfield.fields.field is also zero and vice versa. Why this is happening, this will not happen when there is only one struct like this

union
{
    unsigned int REG;

    struct
    {
        unsigned char toggle : 1;
        unsigned char field : 3;
        unsigned char count : 3;
    } flag;
} bitfield;

Upvotes: 2

Views: 88

Answers (2)

Eraklon
Eraklon

Reputation: 4288

This is the behavior of the union. REG, flag and fields stored in the same memory location which size is the biggest one of them all. If you overwrite one the other ones are owerwritten too. If you would set REG for example to 0xffffffff, so all 1s binary, then flag and fields should also have full 1s in their binary values.

Upvotes: 5

Pierre François
Pierre François

Reputation: 6061

A union is a special data type available in C that allows to store different data types in the same memory location. In your case, toggle and field are using the same bytes. If you don't want this behaviour, you better avoid to use union.

Upvotes: 2

Related Questions