c - 在 union 中写入字节数组并从 int 读取以转换 MISRA C 中的值是否合法?

标签 c language-lawyer unions misra

我想这之前一定有人问过,但我无法得到具体的是/否答案。

我有这个代码片段:

union integer_to_byte
{
    signed int  IntPart;
    unsigned char BytePart[2];
};

typedef union integer_to_byte I2B;

main()
{
   I2B u16VarNo;

   while(1)
   {
       // some code....
       u16VarNo.BytePart[1]= P1;

       // some more code ....
       u16VarNo.BytePart[0]= P2;

       // still more code ...
       if(u16VarNo.IntPart != 0xFFFF)
       {
       }
   }
}

这是在 C 中使用 Unions 的合法方式吗?从我读到的;只有最后分配的 union 部分是有效的。所以“u16VarNo.BytePart[1]”不是确定的?
我编写的代码按预期完美运行,但我想我会得到澄清。

TIA。

最佳答案

Is it legal write to a byte array in a union and read from an int to convert values in MISRA C?



不可以。不得使用 union 。

MISRA C:2004, 18.4 - 不得使用 union 。
MISRA C:2012, 19.2 - 不应使用 union 关键字

MISRA C:2004 中的规则紧随其后:

It is recognised nonetheless that there are situations in which the careful use of unions is desirable in constructing an efficient implementation. In such situations, deviations to this rule are considered acceptable provided that all relevant implementation-defined behaviour is documented. This might be achieved in practice by referencing the implementation section of the compiler manuals from the design documentation.





The use of deviations is acceptable for (a) packing and unpacking of data, for example when sending and receiving messages, and (b) implementing variant records provided that the variants are differentiated by a common field.



您的使用不适合这些情况。

关于c - 在 union 中写入字节数组并从 int 读取以转换 MISRA C 中的值是否合法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60833137/

相关文章:

c - 使用枚举时 c 中出现奇怪的编译错误

c - 指定动态数组初始化

c - strcmp 比较相同的字符串但不进入循环

c++ - void() 和 int() 解析的区别

C 联盟产出不明

c++ - 将结构传递给函数

连续分配与顺序分配

c++ - std::vector of struct:调整 vector 大小后结构成员的初始值是多少?

c - 在 yacc 文件中使用 union

C 嵌套 union 和结构