Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is g++ allowing me to treat this void-function as anything but?

Tags:

c++

gcc

c++11

Why does the following compile in GCC 4.8 (g++)? Isn't it completely ill-formed?

void test(int x)
{
    return test(3);
}

int main() {}
  1. I'm trying to use the result of calling test, which does not exist
  2. I'm trying to return a value from test

Both should be fundamentally impossible — not just UB, as far as I can recall — with a void return type.

The only warning I get is about x being unused, not even anything about a non-standard implicit return type being added.

Live demo

like image 405
Lightness Races in Orbit Avatar asked Jan 04 '14 16:01

Lightness Races in Orbit


People also ask

Why do we use void as it is returning nothing?

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. Some of them are like below.

What does void * func () mean?

Void functions, also called nonvalue-returning functions, are used just like value-returning functions except void return types do not return a value when the function is executed. The void function accomplishes its task and then returns control to the caller. The void function call is a stand-alone statement.

What is a void function in C?

Void functions are created and used just like value-returning functions except they do not return a value after the function executes. In lieu of a data type, void functions use the keyword "void." A void function performs a task, and then control returns back to the caller--but, it does not return a value.

How do you declare a void function in C++?

type function-name (formal parameter type list); A void function with value parameters are declared by enclosing the list of types for the parameter list in the parentheses. To activate a void function with value parameters, we specify the name of the function and provide the actual arguments enclosed in parentheses.


1 Answers

That's allowed by the standard (§6.6.3/3)

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.

like image 70
Mat Avatar answered Sep 28 '22 03:09

Mat