Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is returning void valid code?

Tags:

c++

c

People also ask

Is return void valid?

Return from void functions in C++ The void functions are called void because they do not return anything. “A void function cannot return anything” this statement is not always true. From a void function, we cannot return any values, but we can return something other than values.

What does return in void mean?

In computer programming, when void is used as a function return type, it indicates that the function does not return a value. When void appears in a pointer declaration, it specifies that the pointer is universal. When used in a function's parameter list, void indicates that the function takes no parameters.

Do you have to return for void C?

If a return value isn't required, declare the function to have void return type. If a return type isn't specified, the C compiler assumes a default return type of int . Many programmers use parentheses to enclose the expression argument of the return statement. However, C doesn't require the parentheses.

What is void return type in C++?

When used as a function return type, the void keyword specifies that the function doesn't return a value. When used for a function's parameter list, void specifies that the function takes no parameters. When used in the declaration of a pointer, void specifies that the pointer is "universal."


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.


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.


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
}

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());
  ...
}