2

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;
}
Community
  • 1
  • 1
embedded_guy
  • 1,939
  • 3
  • 24
  • 39
  • Looks sane... if your tame compiler doesn't complain with standards compliance cranked *way* up, I'd use it. – vonbrand Apr 03 '14 at 18:45

1 Answers1

1

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.

vonbrand
  • 11,412
  • 8
  • 32
  • 52
  • 2
    It's no longer undefined. It was undefined in C89, but C99 states that the value is now "unspecified". See defect report #257. – Dietrich Epp Apr 03 '14 at 18:52
  • @DietrichEpp, OK. It won't start nethack anymore, but you still can't depend on it "doing what I consider sane today"... – vonbrand Apr 03 '14 at 19:03