tags:

views:

183

answers:

2

I found out that the following code gets accepted by Visual C++ 2008 and GCC 4.3 compilers:

void foo()
{

}

void bar()
{
  return foo();
}


I am a bit surprised that it compiles. Is this a language feature or is it a bug in the compilers? What do the C/C++ standards say about this?

+16  A: 

It's a language feature of C++

C++ (ISO 14882:2003) 6.6.3/3

A return statement with an expression of type “cv 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.

C (ISO 9899:1999) 6.8.6.4/1

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

Cubbi
+8  A: 

Yes, it is valid code. This is necessary when you have template functions so that you can use uniform code. For example,

template<typename T, typename P>
T f(int x, P y)
{
  return g(x, y);
}

Now, g might be overloaded to return void when the second argument is some particular type. If "returning void" were invalid, the call to f would then break.

zvrba
`T` can't be void, because a parameter cannot be void.
strager
Thanks,I've realized myself a few minutes after that I've given a bad example. Fixed!
zvrba