讓我們假設以下代碼在 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;
}
uj5u.com熱心網友回復:
正如編譯器訊息所說,該函式將呼叫自身,因為在 中printf("%d \n", test(a,b));,代碼test(a,b)呼叫test. 在對 的呼叫中test,該函式將再次呼叫自身,這將永遠重復(直到 C 實作的限制)。
要列印函式的回傳值,請在函式外部執行:
#include <stdio.h>
int test(int a, int b);
int main(void)
{
printf("%d\n", test(2, 3));
}
int test(int a, int b)
{
return a b;
}
uj5u.com熱心網友回復:
錯誤資訊很清楚。測驗函式呼叫自身。在那個呼叫中,它再次呼叫自己,(一次又一次......)。
它永遠不會完成。
這是一種無限回圈,通常稱為無限遞回。
也許你想要的是?
#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", c); // Show the result of the calculation
// but without calling this function again.
return c;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/536632.html
標籤:C功能变量方法新运营商
上一篇:JavaScript-如何將DOM元素放入變數中,即以后函式中的變數?
下一篇:凍結下一次迭代的解值
