1

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

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
tahzibi
  • 77
  • 6
  • Looks like a duplicate of: https://stackoverflow.com/questions/76698227/whats-the-significance-of-a-c-function-declaration-in-parentheses-apparently-fo – brhans Aug 06 '23 at 23:13

2 Answers2

3

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1
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);
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • thanks, but is it possible to define forward declaration of a function inside another function? (and what is the meaning). because I think it has meaning when we declare them at the beginning of a file for example after #includes – tahzibi Aug 06 '23 at 09:05
  • @tahzibi You can do forward declarations almost everywhere. In the global scope, inside functions, even inside statement blocks. – Some programmer dude Aug 06 '23 at 09:52
  • Can you give an applied example, of using forward function declaration inside another function? – tahzibi Aug 06 '23 at 11:35
  • @tahzibi If you need to call a function that is defined (implemented) elsewhere (in another translation unit, or later in the same translation unit). – Some programmer dude Aug 06 '23 at 13:39