I'm going through few C aptitude questions. This one seemed tricky, can any one explain?
struct {
int foo : 4;
} baz;
int *example()
{
return &baz.foo;
}
This is invalid code, but i couldn't figure out the reason.
I'm going through few C aptitude questions. This one seemed tricky, can any one explain?
struct {
int foo : 4;
} baz;
int *example()
{
return &baz.foo;
}
This is invalid code, but i couldn't figure out the reason.
int foo : 4;
declares foo
as a bit-field. One must not take the address of a bit-field.
Section 6.5.3.2 starts:
The operand of the unary
&
operator shall be either a function designator, the result of a[]
or unary*
operator, or an lvalue that designates an object that is not a bit-field and is not declared with the register storage-class specifier.
So applying the address operator to a bit-field is a constraint violation. (It wouldn't even make much sense, since a bit-field need not start at a byte boundary.)
The colon syntax in the struct
declares foo
as a bit-field.
Since a bit-field might be smaller than the architecture's smallest addressable piece of memory (typically the byte on many modern CPU architectures), it's not allowed to take the address of such a member.
Thus, this code fails to compile since it violates that rule.
The foo field is a 4-bit wide bit-field – smaller than a single byte. Pointers can only address whole bytes, so this is invalid. Even if foo was 8 or 32 bits wide (full/aligned bytes on modern architectures) this would still be invalid.
I think if you compile your file you will have solution:
cannot take address of bit-field
Because in memory architecture, each time you use pointer it will to take address where it points to. but baz is just a bit field, so it will be invalid.