Unexpected Warning when Assigning Bit-field to Variable

Viewed 148

This portion of code

typedef struct
{
   unsigned int a : 1;
} bitfield_t;

bitfield_t bitfield = {1};
unsigned char c = bitfield.a;

when compiled with Visual Studio 2019 cl /TC /W4 main.c produces the warning 'initializing': conversion from 'unsigned int' to 'unsigned char', possible loss of data

I don't understand how there can be a loss of data when assigning from a 1-bit field to an 8-bit variable. Does the C standard not guarantee that this assignment be possible and have the expected value c == 1?

1 Answers

Since your struct field is an unsigned int, int is typically 4 bytes wide in memory while unsigned char is typically 1 byte wide. The actual sizes depend on the compiler but what matters is that int uses more bytes than char.

So this message is accurate, you're chopping off 3 bytes when assigning an int to a char.

Related