Search code examples
cpointersfunction-pointersdeclarationfunction-declaration

what does void(*) void and int(*) int mean in C?


Can anyone explain these two lines of code in C:

void (*pfs)(void) = &fs;        
long int (*pfact)(int) = &fact; 

Solution

  • To make these declarations more clear

    void (*pfs)(void)=&fs;
    long int (*pfact)(int)=&fact; 
    

    you can introduce typedef names for function declarations as for example

    typedef void FUNC1( void );
    typedef long int FUNC2( int );
    

    and then write

    FUNC1 *pfs = &fs;
    FUNC2 *pfact = &fact; 
    

    So the original declarations declare pointers to functions of the specified types and initialize them with addresses of the given functions.

    Here is a demonstrative program

    #include <stdio.h>
    
    typedef void FUNC1( void );
    typedef long int FUNC2( int );
    
    void fs( void )
    {
        puts( "Hello Islacine" );
    }
    
    long int fact( int x )
    {
        return x;
    }
    
    int main(void) 
    {
        FUNC1 *pfs = &fs;
        FUNC2 *pfact = &fact;
    
        pfs();
    
        printf( "sizeof( long int ) = %zu\n", sizeof( pfact( 0 ) ) );
    
        return 0;
    }
    

    Its output might look like

    Hello Islacine
    sizeof( long int ) = 8
    

    Take into account that instead of

        FUNC1 *pfs = &fs;
        FUNC2 *pfact = &fact;
    

    or instead of

        void (*pfs)(void)=&fs;        
        long int (*pfact)(int)=&fact; 
    

    you could even write

        FUNC1 *pfs = fs;
        FUNC2 *pfact = fact;
    

    or

        void (*pfs)(void) = fs;        
        long int (*pfact)(int) = fact; 
    

    because in expressions with rare exceptions a function designator is converted to pointer to function.

    You could even write :)

        FUNC1 *pfs = *****fs;
        FUNC2 *pfact = *****fact;
    

    or

        void (*pfs)(void) = *****fs;        
        long int (*pfact)(int) = *****fact; 
    

    From the C Standard (6.3.2.1 Lvalues, arrays, and function designators)

    4 A function designator is an expression that has function type. Except when it is the operand of the sizeof operator65) or the unary & operator, a function designator with type ‘‘function returning type’’ is converted to an expression that has type ‘‘pointer to function returning type’’.