Main Content

MISRA C++:2008 Rule 5-0-19

The declaration of objects shall contain no more than two levels of pointer indirection

Description

Rule Definition

The declaration of objects shall contain no more than two levels of pointer indirection.

Rationale

If you use pointers with more than two levels of indirection, a developer reading the code might find it difficult to understand the behavior of the code.

Polyspace Implementation

Polyspace® flags all declarations of objects that contain more than two levels of pointer indirection.

  • If you use type aliases, the checker includes pointer indirections from the alias in the evaluation of the level of indirection. For instance, in this code snippet, the declaration of var is non-compliant. The type of var is const pointer to a const pointer to a pointer to char, which is three levels of pointer indirection. The declaration of var2 has two levels of pointer indirection and is compliant.

    using ptrToChar = char*;
    
    void func()
    {
        ptrToChar* const* const var = nullptr; //Non-compliant, 3 levels of indirection
        char* const* const var2 = nullptr; //Compliant, 2 levels of indirection
        //...
    }

  • If you pass an array to a function, the conversion of the array to a pointer to the first element of the array is included in the evaluation of the level of indirection. For instance, in this code snippet, parameter arrParam is non-compliant. The type of arrParam is a pointer to a pointer to a pointer to char (three levels of pointer indirection). The declaration of arrVar is compliant because arrVar has type array of pointer to pointer to char (two levels of pointer indirection).

    void func(char** arrParam[])  //Non-compliant
    {
        //...
        char** arrVar[5]; //Compliant
    }

This checker does not flag the use of objects with more than two levels of indirection. For instance, in this code snippet, the declaration of var is non-compliant, but the evaluation of the size of var is compliant.

#include<iostream>


using charToPtr = char*;

void func()
{
    charToPtr* const* const var = nullptr; //Non-compliant
    std::cout << sizeof(var) << std::endl; //Compliant

}

Troubleshooting

If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Check Information

Group: Expressions
Category: Required

Version History

Introduced in R2013b