主要内容

MISRA C:2023 Rule 19.2

The union keyword should not be used

自 R2024a 起

描述

规则定义

The union keyword should not be used 1 .

理由

如果您向某个并集成员写入数据,并读取同一个并集成员,则行为是明确定义的。但如果您读取不同的成员,则行为取决于各成员的相对大小。例如:

  • 如果您读取占用内存更大的并集成员,则读取到的值是未指定的。

  • 否则,值取决于具体实现。

故障排除

如果您预期会出现违规,但未看到该违规,请参阅诊断为何编码规范违规未按预期显示

示例

全部展开

unsigned int zext(unsigned int s)
{
    union                 /* Non-compliant */
    {
        unsigned int ul;
        unsigned short us;
    } tmp;

    tmp.us = s;
    return tmp.ul;        /* Unspecified value */
}

在此示例中,写入的是 16 位的 short 字段 tmp.us,但读取的是更宽的 32 位 int 字段 tmp.ul。使用 union 关键字可能会导致这种未指定行为。因此,该规则禁止使用 union 关键字。

检查信息

组:重叠存储
类别:建议
AGC 类别:建议

版本历史记录

在 R2024a 中推出


1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.

The MISRA coding standards referenced in the Polyspace® Bug Finder™ documentation are from the following MISRA standards:

  • MISRA C:2004

  • MISRA C:2012

  • MISRA C:2023

  • MISRA C++:2008

  • MISRA C++:2023

MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.