Some time ago I ran into a bug that had been dormant for some time. The problem involved expressions where one of the operands is a bit-field.
To demonstrate the problem, I will present a reduced example:
#include <stdio.h>
#include <inttypes.h>
typedef struct {
uint32_t uf1 : 12;
uint32_t uf2 : 12;
uint32_t uf3 : 8;
} BF;
int main( void )
{
BF bf;
uint64_t u1, u2;
bf.uf1 = 0x7ff;
bf.uf2 = ~bf.uf1;
u1 = bf.uf1 << 20;
u2 = bf.uf2 << 20;
printf( "u1: %016" PRIX64 "\n", u1 );
printf( "u2: %016" PRIX64 "\n", u2 );
return( 0 );
}
The troublesome behavior is demonstrated by the lines performing the left shift. We take a 12-bit wide bit-field, shift it left by 20 bits so that the high bit of the bit-field lines up with the high bit of uint32_t, and then convert the result to uint64_t.
The contents of u1 will be predictable. The contents of u2 perhaps not so much. Or more specifically, the resulting value of u2 depends entirely on who you ask.




