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

How can i get the return value from a function called in other function?

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

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;
}

你不能那样使用函数指针。在您的代码中,您将 plus() 的返回值传递给函数 cal(),这是不正确的。 cal() 接受函数指针,而 plus() returns 接受 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;
}

也许您正想做这样的事情?

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;
}