4

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.

William Pursell
  • 204,365
  • 48
  • 270
  • 300

4 Answers4

7
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.)

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
4

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.

unwind
  • 391,730
  • 64
  • 469
  • 606
2

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.

Gokul Nath KP
  • 15,485
  • 24
  • 88
  • 126
1

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.

hqt
  • 29,632
  • 51
  • 171
  • 250