【问题标题】:Print value of function without a variable in CC中没有变量的函数的打印值
【发布时间】:2022-11-17 20:45:29
【问题描述】:

让我们假设以下代码在 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;

}

为什么不能打印 test 的值而不必先将其保存在变量中并打印变量?我收到错误:

function.c:12:1: 错误:通过此函数的所有路径都将调用自身 [-Werror,-Winfinite-recursion]

谢谢!

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

}

【问题讨论】:

  • 这是完全可能的。但是你的函数是无限递归的(正如你的编译器告诉你的那样)。你需要一个方法停止打电话给test()

标签: c function variables methods new-operator


【解决方案1】:

错误信息很清楚。测试函数调用自身。里面调用,它再次调用自己,(一次又一次......)。

它永远不会完成。

这是一种无限循环,通常称为无限递归.

也许你想要的是?

#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 
", c); // Show the result of the calculation
                     // but without calling this function again.
 return c;

}

【讨论】:

    【解决方案2】:

    正如编译器消息所说,该函数将调用自身,因为在printf("%d ", test(a,b)); 中,代码test(a,b) 调用了test。在对 test 的调用中,该函数将再次调用自身,并且这将永远重复(直到 C 实现的限制)。

    要打印函数的返回值,请在函数外部执行:

    #include <stdio.h>
    
    int test(int a, int b);
    
    int main(void)
    {
        printf("%d
    ", test(2, 3));
    }
    
    int test(int a, int b)
    {
        return a+b;
    }
    

    【讨论】:

      猜你喜欢
      • 2021-04-19
      • 1970-01-01
      • 2016-04-11
      • 2015-10-10
      • 1970-01-01
      • 1970-01-01
      • 2010-12-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多