Skip to content

Instantly share code, notes, and snippets.

@hikari-no-yume
Created February 11, 2015 17:19
Show Gist options
  • Save hikari-no-yume/80bb6e66192c38e9abdb to your computer and use it in GitHub Desktop.
Save hikari-no-yume/80bb6e66192c38e9abdb to your computer and use it in GitHub Desktop.
void versus null

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment