3

I'm not sure if this could be compile related, but the compiler I'm using is IAR 7.10.3.

I have a struct like follows:

struct A {
  struct {
    uint8_t x:1;
    uint8_t y:2;
    uint8_t z:5;
  } b;
};

And initializes it like:

struct A a = {
  .b = 0xFF,
};

Now when I look at the struct in memory, only the x bit will be set to '1', the rest will be zero.

Is this how it should behave according to the C standard?

Niklas Norin
  • 355
  • 1
  • 3
  • 9
  • This is similar to [this](http://stackoverflow.com/questions/24936022/designated-initializers-and-compound-literals-for-struct-in-c) recently asked question. – Shafik Yaghmour Jul 24 '14 at 15:53
  • @this he is using `IAR`, and bit-field type can be an implementation-defined type. – ouah Jul 24 '14 at 15:55
  • @this c99 says `A bit-field shall have a type that is a qualified or unqualified version of _Bool, signed int, unsigned int, or some other implementation-defined type.` ... note implementation defined type. – Shafik Yaghmour Jul 24 '14 at 15:55
  • @ShafikYaghmour how? Because I am explicitly initializing '.b'. It seems that this is somehow translated to initializing '.b.x'. I'm still curious if this is how it is supposed to behave. – Niklas Norin Jul 24 '14 at 15:57
  • 1
    @NiklasNorin paragraph 17 which I quote covers this case: `causes the following initializer to begin initialization of the subobject described by the designator. Initialization then continues forward in order, beginning with the next subobject after that described by the designator.` – Shafik Yaghmour Jul 24 '14 at 15:59
  • 1
    By the way your inner struct is not an *anonymous* struct. c11 defines an anonymous struct as an unnamed and untagged inner struct. – ouah Jul 24 '14 at 16:04

1 Answers1

6
struct A a = {
  .b = 0xFF,
};

is parsed by your compiler as

struct A a = {
  .b = {0xFF},
};

which is equivalent to

struct A a = {
  .b = {0xFF, 0, 0},
};

Use:

struct A a = {
  .b = {1, 3, 31},
};

to have all the bits of your bit-fields set to 1. Or use an union with an uint8_t and the inner struct and initialize the first member to 0xFF.

ouah
  • 142,963
  • 15
  • 272
  • 331