In languages like C, C++, C#, Java, and so on, void
is used as the return type of a function that only performs side effects and does not return any value:
void foobar() {
some_state++;
}
In such functions, it is illegal to use any form of return other than a no-value return:
void foobar() {
return; // okay
return null; // compile error
}
This, void
serves to enforce that nothing is returned.
If a return type is declared it is usually implicitly nullable in such languages. However, return;
is not considered equivalent to return null;
:
thing* foobar() {
return; // compile error, must return a value
return null; // okay
}
So, a non-void return type serves to enforce that some value must be returned.