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