为何无法直接打印C语言函数返回值?遇无限递归错误求解
问题:直接打印函数返回值触发无限递归错误原因分析
代码示例
#include <stdio.h> #include <cs50.h> int test (int a, int b); int main(void) { test(2,3); } int test (int a, int b) { int c = a+b; printf("%d\n", test(a,b)); return c; }
错误信息
function.c:12:1: error: all paths through this function will call itself [-Werror,-Winfinite-recursion]
原因分析
你在test函数的printf语句里,错误地再次调用了test(a,b),这会导致无限递归:每次执行到这个printf时,函数都会调用自身,而且没有任何终止条件阻止这个过程——递归永远不会停止,最终会耗尽程序栈空间。
你原本的需求是直接打印函数的返回值,但实际上应该打印已经计算好的变量c,而不是再次调用函数。修正后的printf语句应该是:
printf("%d\n", c);
这样就能直接输出a+b的结果,不会触发递归调用。
内容的提问来源于stack exchange,提问作者Programmingisnewforme
相关产品推荐
相关产品推荐

