Reputation: 99
When playing with functions return values, the following code, compiles and works in g++. There is a method that returns void, which calls in a return statement another function that returns void. My question is why do g++ allow this kind of behavior?
#include <iostream>
void Foo()
{
std::cout << "Foo" << std::endl;
}
void Boo()
{
return ( Foo() );
}
int main()
{
Boo();
return ( 0 );
}
Upvotes: 2
Views: 1376
Reputation: 410
According to CPP Reference, when calling return expression;
:
The expression is optional in functions whose return type is (possibly cv-qualified) void, and disallowed in constructors and in destructors.
Later, they note:
In a function returning void, the return statement with expression can be used, if the expression type is void.
return
can have an expression for a void function as long as the expression is also void, which is what you've done. This could be useful in templates, where the return type of the function may be unknown at the time of writing your function.
Upvotes: 6
Reputation: 2679
void
is a type that can be used interchangeably with other types in certain circumstances. Your example would make perfect sense if Boo
and Foo
returned int
; why should changing the type be a special exception to otherwise correct semantics?
return (Foo())
is essentially saying "return nothing," which is, in fact, Boo
's stated return type. You'll find that
void bar() {
return void();
}
compiles just fine.
Upvotes: 1