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
.