Following code can't be compiled with g++ version 5.4.0 with option -std=c++1y
:
void f(int=0) ;
int main() {
f(); // ok
(*f)(2);// ok
(*f)();// ok c++11; error with c++14: too few arguments to function
return 0;
}
The function declared to have default argument, so what is wrong here? thanks for help.
And why does g++ -c -std=c++11
compile?
A default argument is a value provided in a function declaration that is automatically assigned by the compiler if the calling function doesn't provide a value for the argument. In case any value is passed, the default value is overridden.
There are no default parameters in C. One way you can get by this is to pass in NULL pointers and then set the values to the default if NULL is passed.
The default arguments are used when you provide no arguments or only few arguments while calling a function. The default arguments are used during compilation of program.
In computer programming, a default argument is an argument to a function that a programmer is not required to specify. In most programming languages, functions may take one or more arguments. Usually, each argument must be specified in full (this is the case in the C programming language).
Accepting (*f)()
as valid is a GCC bug. The letter of the standard indicates that using a function name with unary *
should cause the function name to decay into a pointer. The pointer should then be dereferenced to obtain the functions address for the call expression.
But GCC seems clever, and omits the above behavior. It treats (*f)
simply as f
. And calling f
can be done with default arguments.
However, one can force GCC to preform the decay. Unary +
applied on the function name will decay it to a pointer forcefully. So the following two:
(+f)();
(*+f)();
Cause GCC to emit error: too few arguments to function
on either standard revision, in both GCC 7.2 and GCC 6.3.
Default arguments are not a part of function type, so they are discarded when you implicitly convert function to function pointer and then indirect that pointer.
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