Why is this an issue?
When a function does not return an appropriate value, it causes the program to have an undefined behavior. For example, if a function is supposed
to return a value indicating whether a file was successfully opened but does not return any value, the program may continue to execute as if the file
was opened successfully, even though it was not. This can lead to data corruption or other issues that are difficult to diagnose.
Functions with a void return type are not expected to return any value. If they do, it may indicate a programming error.
Exceptions
The rule does not raise an issue:
- when the
return
statement of a void
function is a void
expression.
void foo() {
// ...
}
void bar() {
return foo(); // Compliant by exception
}
- for coroutines, introduced in C++20. Coroutines always declare coroutine objects as return types, but the compiler implicitly creates the
returned object. The coroutine body never contains a
return
statement, as it is disallowed: if a coroutine returns a value, it will use
co_return
.
How to fix it
Code examples
Noncompliant code example
int my_func(int a) {
if (a > 100) {
return; // Noncompliant
}
// Noncompliant
}
Compliant solution
int my_func(int a) {
if (a > 100) {
return a;
}
if (a > 80) {
throw new Exception();
}
return 0;
}
Resources
- MISRA C:2004, 16.8 - All exit paths from a function with non-void return type shall have an explicit return statement with an expression
- MISRA C++:2008, 8-4-3 - All exit paths from a function with non-void return type shall have an explicit return statement with an expression
- MISRA C:2012, 17.4 - All exit paths from a function with non-void return type shall have an explicit return statement with an expression
- MITRE, CWE-394 - Unexpected Status Code or Return Value
- CERT, MSC37-C. - Ensure that control never reaches the end of a non-void function
- CERT, MSC52-CPP. - Value-returning functions must return a value from all exit paths
- CERT, MSC53-CPP. - Do not return from a function declared [[noreturn]]
Related rules
- S6369 - Coroutine should have co_return on each execution path or provide return_void