Function value in c / c ++

Possible duplicate:
How is dereferencing a function pointer?

If we have

void f() { printf("called"); } 

Then the following code will lead to the output of "calledcalled":

 f(); (*f)(); 

I really don't understand how this works ... what is the difference between *f and f ? And why are you calling a function using the latest syntax?

+6
source share
3 answers

There are two ways to call a function in C ++:

By name:

 f(); 

Via function pointer:

 typedef void (*fptr_t)(); fptr_t fptr = &f; (*fptr)(); 

Now, using the operator address for the function name ( &f ), obviously, a pointer to the function is created. But a function name can implicitly convert to a function pointer when certain conditions are met. Therefore, the above code can be written as:

 typedef void (*fptr_t)(); fptr_t fptr = f; // no address-of operator, implicit conversion (*fptr)(); 

The second example is executed in this way, but with the help of a temporary variable, hold the pointer to the function instead of the local local variable.

I prefer to use the address when creating function pointers, the meaning is much clearer.

Related Note. A function call operator automatically searches for a pointer to a function, if any. So this is also legal:

 typedef void (*fptr_t)(); fptr_t fptr = &f; fptr(); 

This is very useful with templates because the same syntax works if you have a pointer to a function or functor (an object that implements operator() ).

And none of the labels work with pointers to elements, there you need explicit address and dereference operators.


In C, @Mehrdad explains that all function calls use a function pointer.

+6
source

The first is somewhat syntactic sugar for the second. Secondly, it is obvious that you are making a call through a pointer, and it is used mainly with function pointers, rather than regular functions, to make the difference more obvious.

+6
source

Just as the type of the array is almost completely equivalent to the corresponding pointer-element type, the type of the function is completely equivalent to the corresponding pointer-type to the function:

 void (*func1)() = f; // function type -> pointer-to-function type void (*func2)() = &f; // pointer-to-function type -> pointer-to-function type 

and

 void (*func)() = ...; func(); // pointer-to-function type + function-call operator (*func)(); // function type + function-call operator 

So in

 (*f)(); 

you look up f (implicitly converted to &f ) and then apply the call function operator.

+2
source

Source: https://habr.com/ru/post/887026/


All Articles