如何从其他函数中调用的函数中获取返回值?

时间:2015-09-07 18:08:04

标签: c pointers function-pointers

如何从其他函数中调用的函数中获取返回值?

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

int cal(int (*f)(int, int)) {         //    Does it correct?
    int ret;
    //  how can I get the return value from the function?
    return ret;
}

int main() {
    int result = cal(plus(1,2));     // I'd like it can be called in this way
    return 0;
}

2 个答案:

答案 0 :(得分:1)

你不能使用那样的函数指针。在您的代码中,您将返回的值从plus()传递给函数cal(),这是不正确的。 cal()plus()返回int时采用函数指针。

这是使用函数指针的方法:

#include <stdio.h> /* don't forget stdio.h for printf */

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

int cal(int (*f)(int, int)) {
    return f(1,2); /* call the function here */
}

int main() {
    int result = cal(&plus); /* the & is not technically needed */
    printf("%d", result);
    return 0;
}

然而,看起来你想要完成的事情可以在没有函数指针的情况下完成。

#include <stdio.h>

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

int main() {
    int result = plus(1,2); /* just call plus() directly */
    printf("%d", result);
    return 0;
}

答案 1 :(得分:1)

也许您正在寻找这样的事情?

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

int cal(int (*f)(int, int), int a, int b) {
    return f(a,b);   // call the function with the parameters
}

int main() {
    int result = cal(plus,1,2);  // pass in the function and its parameters
    return 0;
}
相关问题