c function pointer, another syntax

68 Views Asked by At

In C, when we want to define a function pointer for the following type of functions:

int f(int x, int y);

we define a function pointer variable as

int (*fp)(int, int);

My question is, what is the meaning of the following line in C (without *), because gcc, compile it without error

int (fp)(int, int);

thank you

2

There are 2 best solutions below

4
Some programmer dude On BEST ANSWER
int (fp)(int, int);

is a forward declaration of a function named fp.

It doesn't declare or define a variable. It's like using parentheses around any other name, like for example (x) + (y).

In short, it's the same thing as

int fp(int, int);
0
Vlad from Moscow On

According to the C grammar (the C Standard, 6.7.6 Declarators) a declarator may be enclosed in parentheses

declarator:
    pointeropt direct-declarator

direct-declarator:
    identifier
    ( declarator )
    //...

So this function declaration

int fp(int, int);

may be also written like for example

int (fp)(int, int);

or

int ( (fp)(int, int) );

Usually programmers enclose a function name in parentheses to prevent to use a macro with the same name as the function name by the compiler.

Consider the following program.

#include <stdio.h>

#define fp( x ) return x;

int (fp)( int x )
{
    fp( x );
}

int main( void )
{
    printf( "%d\n", ( fp )( 10 ) );
}

The program output is

10

Without enclosing the function name in parentheses

int fp( int x )
{
    fp( x );
}

the compiler will consider it as a macro and will issue an error. Or on the other hand, if you enclose in parentheses the name fp within the function

int (fp)( int x )
{
    ( fp )( x );
    //^^^^
}

then in this case the function will recursively call itself.