Main Content

MISRA C:2012 Rule 5.3

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

Description

Rule Definition

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

Rationale

If two identifiers have the same name but different scope, the identifier in the inner scope hides the identifier in the outer scope. All uses of the identifier name refers to the identifier in the inner scope. This behavior forces the developer to keep track of the scope and reduces code readability.

Polyspace Implementation

Polyspace® considers two names as distinct if there is a difference between their first 63 characters. In C90, the difference must occur between the first 31 characters. To use the C90 rules checking, use the value c90 for the option C standard version (-c-version). You can change the number of characters compared using the option -code-behavior-specifications. See -code-behavior-specifications.

If the identifier that is hidden is declared in a Standard Library header and you do not provide the header for the analysis, the issue is not shown. To see potential conflicts with identifiers declared in a Standard Library header, provide your compiler implementation of the headers for the Polyspace analysis. See Provide Standard Library Headers for Polyspace Analysis.

Additional Message in Report

Variable XX hides variable XX (FILE line LINE column COLUMN).

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

typedef signed short int16_t;

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

In this example, the identifier i defined in the inner block in func hides the identifier i with function scope.

It is not immediately clear to a reader which i is referred to in the statement i=3.

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 );
}

In this example, the parameter xyz of function func hides the global variable xyz.

It is not immediately clear to a reader which xyz is referred to in the statement g (&xyz ).

Check Information

Group: Identifiers
Category: Required
AGC Category: Advisory

Version History

Introduced in R2014b