Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does C++ not allow passing a void argument to a function having zero parameters?

void f()
{}

void f(int)
{
    return f(); // #1: ok
}

void g(auto fn)
{
    f(fn());
}

int g1()
{
    return 0;
}

void g2()
{}

int main()
{
    g(g1); // #2: ok
    g(g2); // #3: error
}

C++ allows explicitly returning a void value as shown at #1, I think it's elegant and generic.

However, the rule cannot be applied to #3 in the same way.

Why does C++ not allow passing a void argument to a function having zero parameters?

like image 414
xmllmx Avatar asked May 01 '20 08:05

xmllmx


People also ask

Can a void function have no parameters?

The void keyword can be used as a type specifier to indicate the absence of a type or as a function's parameter list to indicate that the function takes no parameters. When used as a type specifier, it is most often used as a function return type to indicate that the function does not return a value.

Can void functions have parameters in C?

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.

Can a function have 0 parameters?

The lesson brief states that “Functions can have zero, one or more parameters”.

What will happen when we use void argument passing?

What will happen when we use void in argument passing? Explanation: As void is not having any return value, it will not return the value to the caller.


1 Answers

Because the language specifies that each argument expression in the call initialises a parameter of the function

[expr.call/7]

When a function is called, each parameter is initialized with its corresponding argument.

In a function of no parameters, there is no first parameter to initialise, and even if there were, void is a type with no values.

like image 107
Caleth Avatar answered Sep 30 '22 09:09

Caleth