Main Content

MISRA C:2023 Rule 17.2

Functions shall not call themselves, either directly or indirectly

Since R2024a

Description

Rule Definition

Functions shall not call themselves, either directly or indirectly.

Rationale

Variables local to a function are stored in the call stack. If a function calls itself directly or indirectly several times, the available stack space can be exceeded, causing serious failure. Unless the recursion is tightly controlled, it is difficult to determine the maximum stack space required.

Polyspace Implementation

The checker reports each function that calls itself, directly, indirectly, or through a function pointer. Even if several functions are involved in one recursion cycle, each function is individually reported.

You can calculate the total number of recursion cycles using the code complexity metric Number of Recursions.

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

void foo1(int);
void foo2(int);

void foo1( int n ) {     /* Non-compliant - Indirect recursion foo1->foo2->foo1... */
    if (n > 0) {
        foo2(n);
        foo1(n);               /* Non-compliant - Direct recursion */
        n--;
    }
}

void foo2( int n ) { /* Non-compliant - Indirect recursion foo2->foo1->foo2... */
    foo1(n);
}

In this example, the rule is violated because of:

  • Direct recursion foo1foo1.

  • Indirect recursion foo1foo2foo1.

  • Indirect recursion foo2foo1foo2.

Note that the location of the rule violation is different for direct and indirect recursions:

  • When a function calls itself directly, the rule violation is shown on the function call.

  • When several functions are involved in an indirect recursion chain, for every function in the chain, a rule violation is shown on the function signature in the function body.

Check Information

Group: Function
Category: Required
AGC Category: Required

Version History

Introduced in R2024a