Is it valid to use a C99-style designated initializer list to initialize the members of a bit field within a union in the following way?

StackOverflow https://stackoverflow.com/questions/22845729

  •  27-06-2023
  •  | 
  •  

Вопрос

When I wrote a question regarding PC-Lint, I had made an assumption that the following initialization is valid in C99. @JoachimPileborg mentioned that it may not be and I haven't been able to find any information that provides a good example one way or another. I know that it compiles and behaves as I expect, I would just like to know for certain that it is proper C99 code.

Is this a valid way to initialize the following union in C99?

typedef union
{
    struct
    {
        unsigned int a : 4;
        unsigned int b : 4;
        unsigned int c : 4;
        unsigned int d : 4;
    } bits;
    unsigned short value;
} My_Value;

int main (void)
{
    My_value test[] =
    {
        {
            .bits.a = 2,
            .bits.b = 3,
            .bits.c = 2,
            .bits.d = 3,
        },
        {
            .bits.a = 1,
            .bits.b = 1,
            .bits.c = 1,
            .bits.d = 0,
        },
    };

    /* Do something meaningful. */

    return 0;
}
Это было полезно?

Решение

Looks sane... if your tame compiler doesn't complain with standards compliance cranked way up, I'd use it. Much more worrying is that you presumably are trying to overlay value and bits, and stuffing data into one alternative of an union an taking it out of the other is undefined. Endianness aside, the union will probably use up a full word, and very well could have the value at one end and the bits at the other (depending on available instructions and their convenience or timing). The standards declare this undefined precisely to give implementations such leeway.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top