I need help with understanding this code using recursion.
int power(int n1,int n2);
int main()
{
int base, exp;
printf("Enter base number: ");
scanf("%d",&base);
printf("Enter power number(positive integer): ");
scanf("%d",&exp);
printf("%d^%d = %d", base, exp, power(base, exp));
return 0;
}
int power(int base,int exp)
{
if ( exp!=1 )
return (base*power(base,exp-1));
}
The code works fine but I don't understand why it still manages to return a value when exp is 1 even when the condition in the function body evaluates to false, so I think it shouldn't return anything then.
For example, if the function is called in the main() function and I assign the values of 5 and 1 to base and exp respectively, I expect that I shouldn't get a return value because exp is 1 and my function returns something only if exp !=1 and also, there is no else part in the function body to cover the case when exp is 1.
I know about C returning garbage values when the return value is not specified but in this case, it returns the right answer and I tested it several times. For example, when I call it in the main function with base=7 and exp=1, it returns 7 as my answer and even with other "base" values, it always returns the base which is the right answer. And that exactly is my source of confusion - How is C managing to return the right answer to me when the IF clause of the function body evaluates to false...
I guess I'm missing something here.
Actually your function is Undefined Behaviour, because of is not returning nothing in case of
exp == 1The value you have in return to your main function is something random.