First and foremost, returning void
can be helpful when writing templates.
You typically don't do it if you know that a function returns void
, but it's helpful that it's legal:
template <typename T, typename F>
auto apply(T x, F f) {
// if f returns void, the return type of apply is deduced to void, and the following
// return statement is legal
return f(x);
}
This example may be a bit artificial, but in practice, returning void
simplifies the implementation of std::apply
.
Another use case is making switch
statements more compact:
void one(), two(), three();
void before(int x) {
switch (x) {
case 1:
one();
break;
case 2:
one();
break;
case 3:
one();
break;
}
}
void after(int x) {
switch (x) {
case 1: return one();
case 2: return two();
case 3: return three();
}
}
Technically, before
could also have just one line per case, but putting multiple statements on a single line often conflicts with style guides and/or auto-formatters.