Taking the address of the bit field

I look through a few questions about the ability. It seemed complicated, can anyone explain?

struct { int foo : 4; } baz; int *example() { return &baz.foo; } 

This is the wrong code, but I could not understand the reason.

+4
source share
4 answers

The foo field is a 4-bit bit field - less than one byte. Pointers can only process integer bytes, so this is not true. Even if foo is 8 or 32 bits wide (full / aligned bytes on modern architectures), this will still be invalid.

+2
source
 int foo : 4; 

declares foo as a bit field. You cannot accept the address of a bit field.

Section 6.5.3.2 begins:

The operand of the unary operator & must be either the designation of the function, the result of the operator [] or unary * , or lvalue, which designates an object that is not a bit field and is not declared using the register storage class specifier.

Thus, using an address operator in a bit field is a violation of the restriction. (This doesn’t even make much sense, since the bit field does not need to start at the byte boundary.)

+7
source

The colon syntax in the struct declares foo as a bit field.

Since the bit field may be smaller than the architecture of the least addressable part of the memory (usually bytes on many modern processor architectures), it is not allowed to accept the address of such a member.

Therefore, this code does not compile because it violates this rule.

+4
source

I think that if you compile your file, you will have a solution:

 cannot take address of bit-field 

Because in the memory architecture, every time you use a pointer, it will take the address it points to. but baz is just a bit field, so it will be invalid.

+1
source

All Articles