主要内容

本页翻译不是最新的。点击此处可查看最新英文版本。

MISRA C:2012 Rule 8.9

An object should be declared at block scope if its identifier only appears in a single function

描述

规则定义

An object should be declared at block scope if its identifier only appears in a single function 1 .

理由

如果您在模块作用域内声明一个对象,那么您或其他人在模块外无意中访问该对象的可能性较小。

Polyspace 实现

规则检查项会标记仅在一个函数中访问但在文件作用域中声明的 static 对象。

故障排除

如果您预计存在违规,但未看到该违规,请参阅Diagnose Why Coding Standard Violations Do Not Appear as Expected

示例

全部展开

static int ctr;   /* Non compliant */

int checkStatus(void);
void incrementCount(void);

void incrementCount(void) {
    ctr=0;
    while(1) {
        if(checkStatus())
            ctr++;
    }
}

在此示例中,ctr 的声明不合规,因为它在文件作用域内声明,但仅在函数 incrementCount 中使用。应在 incrementCount 体中声明 ctr,以符合 MISRA C™ 的要求。

检查信息

组:声明和定义
类别:建议
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.