主要内容

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

MISRA C++:2008 Rule 3-4-1

An identifier declared to be an object or type shall be defined in a block that minimizes its visibility

描述

规则定义

An identifier declared to be an object or type shall be defined in a block that minimizes its visibility. 1

理由

在尽可能小的模块作用域内定义变量,可以降低这些变量日后被意外访问的可能性。

例如,如果某个对象仅在一个函数中访问,请将该对象声明为该函数的局部对象。

Polyspace 实现

规则检查项会判断某个对象是否仅在一个模块中使用。如果对象在一个模块中使用,但在该模块外部定义,检查项将判定为违规。

故障排除

如果您预计存在违规,而 Polyspace® 未报告该违规,请参阅Diagnose Why Coding Standard Violations Do Not Appear as Expected

示例

全部展开

static int countReset; //Noncompliant

volatile int check;

void increaseCount() {
    int count = countReset;
    while(check%2) {
     count++;
    }
}

在此示例中,变量 countReset 声明为全局变量,且仅在一个函数中使用。合规的解决方案是将变量声明为函数的局部变量,以降低其可见性。

检查信息

组:基本概念
类别:必需

版本历史记录

在 R2013b 中推出


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.