Main Content

MISRA C:2023 Rule 8.9

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

Since R2024a

Description

Rule Definition

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

Rationale

If you declare an object at block scope, you or someone else is less likely to access the object inadvertently outside the block.

Polyspace Implementation

The rule checker flags static objects that are accessed in one function only but declared at file scope.

Troubleshooting

If you expect a rule violation but do not see it, refer to Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

static int ctr;   /* Non compliant */

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

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

In this example, the declaration of ctr is noncompliant because it is declared at file scope but used only in the function incrementCount. Declare ctr in the body of incrementCount to be MISRA C™-compliant.

Check Information

Group: Declarations and Definitions
Category: Advisory
AGC Category: Advisory

Version History

Introduced in R2024a