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?
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.
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.
The lesson brief states that “Functions can have zero, one or more parameters”.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With