Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dereferencing a function with default arguments - C++14 vs C++11

Tags:

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?

like image 819
Pavlo Rudenko Avatar asked Oct 30 '17 10:10

Pavlo Rudenko


People also ask

What are default arguments C++?

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.

Does C default argument?

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.

What is the principle reason for using default arguments in the function?

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.

What do you mean by default argument?

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).


2 Answers

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.

like image 152
StoryTeller - Unslander Monica Avatar answered Oct 21 '22 01:10

StoryTeller - Unslander Monica


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.

like image 38
Alex Guteniev Avatar answered Oct 21 '22 00:10

Alex Guteniev