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?

天大地大妈咪最大 提交于 2019-12-11 01:35:19

问题


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;
}

回答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.



来源:https://stackoverflow.com/questions/22845729/is-it-valid-to-use-a-c99-style-designated-initializer-list-to-initialize-the-mem

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!