zhan Wang
zhan Wang

Reputation: 11

Can the function itself serve as a parameter to another function?

this is my code:

#include <stdio.h>

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


void fun1(int a,int b,int (*c)(int a,int b)){//Standard writing method
    int sum=getsum(a,b);
    printf("%d\n",sum);
}
void fun2(int a,int b,int c(int a,int b)){//The function itself serves as a parameter
    int sum=getsum(a,b);
    printf("%d\n",sum);
}

int main(){
    int a=1;
    int b=2;
    
    fun1(a,b,getsum);
    fun2(a,b,getsum);
    return 0;
}

Both of these functions yield the same result after running The results are all equal to 3 The c parameter of the first function is written in the standard way, while the second one directly represents the function itself

I just want to know if both of these writing methods are correct

Upvotes: 1

Views: 62

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311088

From the C Standard (6.7.6.3 Function declarators (including prototypes) Constraints)

8 A declaration of a parameter as "function returning type" shall be adjusted to "pointer to function returning type", as in 6.3.2.1.

Thus these two function declarations

void fun1(int a,int b,int c(int a,int b));
void fun1(int a,int b,int (*c)(int a,int b));

declare the same one function. For the first declaration the compiler itself adjusts the parameter having the function type to a parameter having a pointer type to the function type.

In function declarations that are not at the same time its definition you may ommit a parameter name. So the above declarations you may also write like

void fun1(int a,int b,int (int a,int b));
void fun1(int a,int b,int (*)(int a,int b));

It seems in bodies of your functions you mean

int sum=c(a,b);

instead of

int sum=getsum(a,b);

Pay attention to that such an adjustment of a function specifiers does not occur outside function parameter lists.

Consider the following demonstration program.

#include <stdio.h>

typedef int Fn( int, int );
typedef int ( *pFn )( int, int );

Fn getsum;

pFn p_getsum = getsum;

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

int main( void )
{
    int x = 1, y = 2;

    printf( "%d + %d = %d\n", x, y, getsum( x, y ) );

    x = y; y = 3;

    printf( "%d + %d = %d\n", x, y, p_getsum( x, y ) );
}

In this declaration

Fn getsum;

the typedef name Fn is not adjusted to a pointer type. Here is declared the function getsum.

Upvotes: 2

Related Questions