chhx001
chhx001

Reputation: 109

Which is the right style to use function pointer?

Sorry, but I'm a bit confused about using function pointers. I typed 3 functions which use function pointer in different ways, but incredibly they all worked.

Here is my code:

#include <stdio.h>
#include <stdlib.h>

typedef int(*pfun)(int a, int b);

int add(int a, int b)
{
    return a + b;
}

int f1()
{
    pfun fun = add;
    return fun(3, 4);
}

int f2()
{
    pfun fun = &add;     //Why did't compiler report an error?
    return fun(3, 4);   //Why it could work? The value in fun should be a pointer of function pointer.
}

int f3()
{
    pfun fun = &add;
    return (*fun)(3, 4);    //Why did't compiler report an error?

}

int main()
{
    printf("%d,%d,%d\n", f1(),f2(),f3());
    system("pause");
    return 0;
}

The output is 7,7,7 with no compile error in VS2017.

Upvotes: 4

Views: 64

Answers (2)

Swordfish
Swordfish

Reputation: 13134

There is no difference between add and &add. Both expressions represent the adress of the function.

As for

fun(3, 4);
// vs.
(*fun)(3, 4);

it doesn't matter whether the function pointer is dereferenced implicitly or you do it explicitly.

Upvotes: 1

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215193

In f2 your comment is wrong. &add could not possibly be a pointer-to-pointer; what pointer object would it point to? Likewise, given char array[N];, &array is not a pointer-to-pointer. It has pointer-to-array type. Both function and array type identifiers evaluate to pointers (pointer-to-function or pointer-to-first-element, respectively) in most contexts, but that does not mean that they have pointer type themselves.

In f3, *fun is an expression evaluating to a function, which always converts implicitly to a pointer to the function. There is simply no such thing as an expression with function type. Therefore, ****************fun also evaluates to the same thing as fun (a pointer to add).

Note that the function call operator () takes as its operand an expression with pointer-to-function type. Whenever you call a function by its identifier, you are using a function pointer.

Per the language, none of these forms are any more "right" than any other, but I think most C programmers find use of & and * operators at best redundant (if not misleading) with functions, and would consider f1 the best.

Upvotes: 3

Related Questions