Main Content

MISRA C++:2008 Rule 8-4-3

All exit paths from a function with non-void return type shall have an explicit return statement with an expression

Description

Rule Definition

All exit paths from a function with non-void return type shall have an explicit return statement with an expression.1

Rationale

When you declare a function with a non-void return type, the code expects the function to return a value of the declared return type. The absence of a return value can cause incorrect logic, especially when the code relies on a specific return value. Not returning a value can also cause undefined behavior.

Polyspace Implementation

The checker reports a rule violation whenever a function with a non-void return does not contain an explicit return statement that provides a value.

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 code, the code expects the function calculate() to return an integer value. calculate() contains an if statement and returns a value only when the value of x is greater than zero. However, if the value of x is less than or equal to zero, the function exits without returning a value, causing undefined behavior.

int calculate(int x) {
    if (x > 0) {
        return x * 2;
    }
}                        //Noncompliant

Check Information

Group: Declarators
Category: Required

Version History

Introduced in R2013b


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.