开发者

value of function in c/C++ [duplicate]

开发者 https://www.devze.com 2023-03-02 13:26 出处:网络
This question already has answers here: 开发者_StackOverflow中文版 Closed 11 years ago. Possible Duplicate:
This question already has answers here: 开发者_StackOverflow中文版 Closed 11 years ago.

Possible Duplicate:

How does dereferencing of a function pointer happen?

If we have

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

Then the following code will result in output of "calledcalled":

f();
(*f)();

I don't really understand how this works…what is the difference between *f and f? And why would you call a function using the latter syntax?


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

By name:

f();

Through a function pointer:

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

Now, using the address-of operator on a function name (&f) obviously creates a function pointer. But the function name can implicitly convert to a function pointer when certain conditions are met. So the above code could be written as:

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

Your second example is doing exactly this, but using a temporary variable to hold the function pointer instead of a named local variable.

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

A related note: The function call operator will automatically dereference a function pointer if one is provided. So this also is legal:

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

That's pretty useful with templates, because the same syntax works whether you have a function pointer or a functor (object implementing operator()) passed in.

And neither shortcut works with pointer-to-members, there you NEED explicit address-of and dereference operators.


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


The first one is somewhat of a syntactic sugar for the second one. The second one makes it obvious that you're making the call through a pointer, and it's used mainly with function pointers rather than regular functions, to make the distinction more obvious.


Just as an array type is almost entirely equivalent to the corresponding pointer-to-element type, a function type is entirely equivalent to the corresponding pointer-to-function type:

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

and also

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

So, in

(*f)();

you're dereferencing f (implicitly converted to &f), and then apply the function-call operator.

0

精彩评论

暂无评论...
验证码 换一张
取 消