Main Content

MISRA C:2023 Rule 15.5

A function should have a single point of exit at the end

Since R2024a

Description

Rule Definition

A function should have a single point of exit at the end.

Rationale

This rule requires that a return statement must occur as the last statement in the function body. Otherwise, the following issues can occur:

  • Code following a return statement can be unintentionally omitted.

  • If a function that modifies some of its arguments has early return statements, when reading the code, it is not immediately clear which modifications actually occur.

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

#define MAX ((unsigned int)2147483647)
#define NULL (void*)0

typedef unsigned int bool_t;
bool_t false = 0;
bool_t true = 1;

bool_t f1(unsigned short n, char *p) {          /* Non-compliant */
    if(n > MAX) {
        return false;
    }

    if(p == NULL) {
        return false;
    }

    return true;
}

In this example, the rule is violated because there are three return statements.

Correction — Use Variable to Store Return Value

One possible correction is to store the return value in a variable and return this variable just before the function ends.

#define MAX ((unsigned int)2147483647)
#define NULL (void*)0

typedef unsigned int bool_t;
bool_t false = 0;
bool_t true = 1;
bool_t return_value;

bool_t f2 (unsigned short n, char *p) {         /* Compliant */
    return_value = true;
    if(n > MAX) {
        return_value = false;
    }

    if(p == NULL) {
        return_value = false;
    }

    return return_value;
}

Check Information

Group: Control Flow
Category: Advisory
AGC Category: Advisory

Version History

Introduced in R2024a

expand all