【问题标题】:How can i get the return value from a function called in other function?如何从其他函数中调用的函数获取返回值?
【发布时间】:2015-12-03 07:52:55
【问题描述】:

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

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

【问题讨论】:

  • int f(void) { return g(); }?请说明您想要完成的任务。

标签: c pointers function-pointers


【解决方案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;
}

【讨论】:

  • 这就是问题所在! “您正在将返回值从 plus() 传递给函数 cal()”谢谢。我正在与 cal() 本身作斗争。
【解决方案2】:

也许你想做这样的事情?

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

【讨论】:

  • 不清楚他们到底想做什么,但这是有道理的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-05
  • 2013-10-24
  • 2014-05-28
  • 2015-08-25
  • 1970-01-01
相关资源
最近更新 更多