开发者

function within a function in c [closed]

开发者 https://www.devze.com 2023-03-11 15:28 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

In the function doubleadd i want the result as the summation of x and function add

#include <stdio.h>

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

int doublea开发者_开发百科dd(int x,int y=(*add)(int a,int b))
{ return (x+y); }

void main()
{
    void (*ptr)(int,int);
    ptr=add;
    int y=ptr(5,7);
    printf("%d",y);
    y=doubleadd(3,ptr(5,7));
}

please help me with this problem


You don't need to do all that mess! This will be fine:

y = doubleadd(3, add(5,7));

and the prototype of doubleadd is

int doubleadd(int x, int y) { ... }

you can pass complex expressions as parameters, too


In the unlikely event you want to turn your C code into some bastard child of a functional language:

#include <stdio.h>

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

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

int doubleadd(int x, addfun f, int a, int b ) { 
    return x + f( a, b ); 
}

int main() {
    addfun fn = add;
    int y = doubleadd(3, fn,  5, 7 );
    printf( "%d\n", y );
}
0

精彩评论

暂无评论...
验证码 换一张
取 消