Return void type in C and C++ Return void type in C and C++ c c

Return void type in C and C++


C11, 6.8.6.4 "The return statement":

A return statement with an expression shall not appear in a function whose return type is void.

No, you may not use an expression, even if it is of void type.

From the foreword of the same document:

Major changes in the second edition included:

[...]

  • return without expression not permitted in function that returns a value (and vice versa)

So this was a change from C89 -> C99 (the second edition of the language standard), and has been that way ever since.


C++14, 6.6.3 "The return statement":

A return statement with an expression of non-void type can be used only in functions returning a value [...] A return statement with an expression of type void can be used only in functions with a return type of cv void; the expression is evaluated just before the function returns to its caller.

Yes, you may use an expression if it is of void type (that's been valid since C++98).


This code is allowed in C++ but not allowed in C

From Return statement @ cppreference

In a function returning void, the return statement with expression can be used, if the expression type is void.


OTOH in C11 specs draft n1570:

Major changes in the second edition included:

return without expression not permitted in function that returns a value (and vice versa)

(return with expression not permitted in function that returns a void)

and 6.8.6.4 return

A return statement with an expression shall not appear in a function whose return type is void. A return statement without an expression shall only appear in a function whose return type is void.

(even if the expression evaluates to void)


C++ allows something like that:

void f() {    return void();}

While C does not. That's why a warning is issued if you compile it a ISO C rather than ISO C++. This is formally described as:

A return statement with an expression of type void can be used only in functions with a return type of cv void