メインコンテンツ

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

根拠

最低限のブロック スコープで変数を定義すると、それらの変数に後で意図せずアクセスされる可能性が減ります。

たとえば、1 つの関数でのみオブジェクトにアクセスすることを意図している場合、そのオブジェクトを関数のローカルで宣言します。

Polyspace 実装

ルール チェッカーは、オブジェクトが 1 つのブロックでのみ使用されているかどうかを判別します。オブジェクトが 1 つのブロックで使用されているが、そのブロックの外側で定義されている場合、チェッカーは違反を報告します。

トラブルシューティング

ルール違反が想定されるものの、Polyspace® から報告されない場合は、コーディング規約違反が想定どおりに表示されない理由の診断を参照してください。

すべて展開する

static int countReset; //Noncompliant

volatile int check;

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

この例では、変数 countReset がグローバルに宣言されていますが、1 つの関数でしか使用されていません。準拠するソリューションでは、可視性を減らすためにその変数を関数のローカルで宣言します。

チェック情報

グループ: Basic Concepts
カテゴリ: 必要

バージョン履歴

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.