它是有效使用C99风格的指定初始化列表按以下方式工会中来初始化位域的成员? [英] 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?

查看:271
本文介绍了它是有效使用C99风格的指定初始化列表按以下方式工会中来初始化位域的成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我写了<一个href=\"http://stackoverflow.com/questions/22823277/how-do-i-sup$p$pss-pc-lint-errors-for-c99-style-initialization-of-structure-membe\">question关于PC-林特,我做了一个假设,即下列初始化是C99有效。 @JoachimPileborg提到,它可能不是,我一直没能找到一个很好的例子这样或那样的任何信息。我知道,它编译和行为如我所料,我只是想知道肯定是正确的C99 code。

这是初始化以下工会C99的有效方法是什么?

 的typedef工会
{
    结构
    {
        unsigned int类型一:4;
        unsigned int类型A:4;
        unsigned int类型C:4;
        unsigned int类型D:4;
    }位;
    无符号短值;
} MY_VALUE;INT主要(无效)
{
    MY_VALUE测试[] =
    {
        {
            .bits.a = 2,
            .bits.b = 3,
            .bits.c = 2,
            .bits.d = 3,
        },
        {
            .bits.a = 1,
            .bits.b = 1,
            .bits.c = 1,
            .bits.d = 0,
        },
    };    / *做些有意义的事。 * /    返回0;
}


解决方案

看起来神志清醒...如果你驯服的编译器不符合标准符合抱怨手摇的办法的时候,我会用它。更令人担忧的是,你presumably试图覆盖,及填充数据到一个替代方案一个工会的取出来对方是的未定义的。字节序之外,工会可能会使用一个完整的字,和很好的可以在一端与 C>在另一(取决于可用的指令和他们的方便或定时)。该标准pcisely声明这个不确定的$ P $给实现这样的余地。

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.

这篇关于它是有效使用C99风格的指定初始化列表按以下方式工会中来初始化位域的成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆