Main Content

MISRA C++:2023 Rule 9.6.5

A function with non-void return type shall return a value on all paths

Since R2024b

Description

Rule Definition

A function with non-void return type shall return a value on all paths.

Rationale

If a function has a non-void return type, it is expected to return a value. If the execution of the function body goes through a path where a return statement is missing, the function return value is indeterminate. Subsequent computations with this return value can lead to unpredictable results.

Polyspace Implementation

The rule checker reports a violation when a function with a non-void return type does not return a value on at least one execution path (unless the function is explicitly specified as [[noreturn]]). The violation is reported on the closing brace of the function body.

For instance, the violation occurs when a function contains a return statement inside one branch of an if-else statement. If this function does not have any other return statement, a path that bypasses this branch does not return a value.

The checker does not report a violation if a function does not return a value because of a deliberate infinite loop such as while(1).

Troubleshooting

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

Examples

expand all

In this example, the function handleError() does not contain a return statement at the end but instead has several return statements inside a switch block. All case clauses in the switch block contain return statements but not the default clause. An execution path that bypasses all case clauses and goes through the default clause leads to the function handleError() not returning a value.

#include <cstdint>

enum errorLevel {LOW, MEDIUM, HIGH, UNSPECIFIED};

uint32_t handleError(enum errorLevel currentErrorLevel, uint32_t currentValue)
{
    switch(currentErrorLevel)
        {
        case LOW:
            return currentValue > 0? currentValue: 0;
            break;
        case MEDIUM:
            return currentValue > 0? currentValue: -currentValue;
            break;
        case HIGH:
            return currentValue > 0? currentValue: -currentValue;
            break;
        default:
            
        }
} // Noncompliant

Check Information

Group: Statements
Category: Required

Version History

Introduced in R2024b