主要内容

本页采用了机器翻译。点击此处可查看最新英文版本。

MISRA C:2012 Rule 5.3

An identifier declared in an inner scope shall not hide an identifier declared in an outer scope

描述

规则定义

An identifier declared in an inner scope shall not hide an identifier declared in an outer scope 1 .

理由

如果两个标识符具有相同的名称但作用域不同,则内层作用域中的标识符会隐藏外层作用域中的标识符。所有对标识符名称的引用均指代其所在的内部作用域中的标识符。这种行为迫使开发人员必须跟踪作用域,从而降低了代码的可读性。

Polyspace 实现

如果两个名称的前 63 个字符之间存在差异,则 Polyspace® 会将它们视为不同的名称。在 C90 中,差异必须出现在前 31 个字符之间。要使用 C90 规则检查,请为 C 标准版本 (-c-version) 选项使用 c90 值。您可以使用 -code-behavior-specifications 选项更改比较的字符数。请参阅 -code-behavior-specifications

如果隐藏的标识符在标准库头文件中声明,而您未提供头文件进行分析,则不会显示该问题。要查看与标准库头文件中声明的标识符之间的潜在冲突,请为 Polyspace 分析提供编译器的头文件实现。请参阅为 Polyspace 分析提供标准库头文件

报告中的补充消息

变量 XX 隐藏变量 XX(文件行 LINE 列 COLUMN)。

故障排除

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

示例

全部展开

typedef signed short int16_t;

void func( void )
{
    int16_t i;
    {
        int16_t i;				/* Non-compliant */
        i = 3;
    }
}

在此示例中,在 func 的内部模块中定义的标识符 i 隐藏了函数作用域中的标识符 i

对于读者而言,声明 i=3 中所指的 i 并不立即明确。

typedef signed short int16_t;

struct astruct
{
    int16_t m;
};

extern void g ( struct astruct *p );
int16_t xyz = 0;

void func ( struct astruct xyz )  /* Non-compliant */
{
    g ( &xyz );
}

在此示例中,函数 func 的参数 xyz 隐藏了全局变量 xyz

对于读者而言,声明 g (&xyz ) 中所指的 xyz 并不立即明确。

检查信息

组:标识符
类别:必需
AGC 类别:建议

版本历史记录

在 R2014b 中推出


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.