let's assume the following code in 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;
}
why is it not possible to print the value of test without having to save it in a variable before and print the variable? I get the error:
function.c:12:1: error: all paths through this function will call itself [-Werror,-Winfinite-recursion]
Thank you!
#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;
}
CodePudding user response:
The error message is quite clear. The test-function calls itself. And inside that call, it calls itself again, (and again, and again...).
It will never complete.
This is a type of infinite loop, commonly called infinite recursion.
Perhaps what you want is?
#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;
}
CodePudding user response:
As the compiler message says, the function will call itself, because, in printf("%d \n", test(a,b));
, the code test(a,b)
calls test
. Inside that call to test
, the function will call itself again, and this will repeat forever (up to the limits of the C implementation).
To print the return value of the function, do it outside the function:
#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;
}