Is returning void valid code?

C++C

C++ Problem Overview


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?

C++ Solutions


Solution 1 - C++

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.

Solution 2 - C++

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.

Solution 3 - C++

This is valid and can be quite useful for example to create cleaner code in situations when you want to do some error handling before returning:

void ErrRet(int code, char* msg)
{
   // code logging/handling error
}
void f()
{
   if (...) return ErrRet(5, "Error Message !");
   // code continue
}
   
   

Solution 4 - C++

Valid indeed. I use it often for input validation macros:

#define ASSERT_AND_RETURN_IF_NULL(p,r) if (!p) { assert(p && "#p must not be null"); return r; }

bool func1(void* p) {
  ASSERT_AND_RETURN_IF_NULL(p, false);
  ...
}

void func2(void* p) {
  ASSERT_AND_RETURN_IF_NULL(p, void());
  ...
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKarel PetranekView Question on Stackoverflow
Solution 1 - C++CubbiView Answer on Stackoverflow
Solution 2 - C++zvrbaView Answer on Stackoverflow
Solution 3 - C++kofifusView Answer on Stackoverflow
Solution 4 - C++liordaView Answer on Stackoverflow