I came across a question in a test series, which when I solved manually according to my knowledge of C programming, should give an output which wasn't matching with any of the options given.
My output = ' ++++ '
Question: Output of following c program is?
#include <stdio.h>
int f(int x)
{
if(x==2){ return 2; }
else{ printf("+"); f(x-1); }
}
int main()
{
int n = f(6);
printf("%d",n);
return 0;
}
Options:
My logic: Because in the end f(6) doesn't explicitly return anything [only f(2) returns the value 2 to f(3)], the output should only contain the 4 times '+' due to each call f(6), f(5), f(4) and f(3).
Below are some test code and their outputs screenshots i tried on online c compilers - 'codechef' and 'onlinegdb' - but i couldnt make sense of their outputs either. Please help!
codechef
onlinegdb 1
onlinegdb 2
If a function is defined to return a value and it doesn't, then attempting to use the returned value results in undefined behavior.
This is documented in section 6.9.1p12 of the C standard:
If the
}
that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined.
This basically means that the result is not predictable and/or consistent.