Contenido principal

MISRA C++:2023 Rule 9.6.5

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

Since R2024b

Description

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

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. Execution paths that bypass the default clause lead 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:
            //....
            break;
        case MEDIUM:
            //...
            break;
        case HIGH:
           //...
            break;
        default:
            return 0;
            
        }
} // Noncompliant

Check Information

Group: Statements
Category: Required
PQL Name: std.misra_cpp_2023.R9_6_5

Version History

Introduced in R2024b


1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.

The MISRA coding standards referenced in the Polyspace Bug Finder™ documentation are from the following MISRA standards:

  • MISRA C:2004

  • MISRA C:2012

  • MISRA C:2023

  • MISRA C++:2008

  • MISRA C++:2023

MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.