This question already has answers here:
Implicit int return value of C function
(7 answers)
Closed 7 years ago.
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 == 1
The value you have in return to your main function is something random.
You may warned by the compiler in the declaration int power(int base,int exp)
No return, in function returning non-void
Hence, you will get undefined behavior, when you call power() with exp = 1.
Note that: Your power() will fall into recursion trap if exp is negative.
In your case, for exp having value 1, there is no return statement. If the return value of that call is used in the caller function, program shows UB.See note below
That said, the issue will also hold true in case you're calling power() with exp value something other than 1, as power() will end up calling itself with exp as 1 at some point of time.
Finally, exp being an int, it can accept a negative value and go into infinite loop, only to create stack overflow by infinite recursion.
Note: As per the C11 standard, if the function is terminated by reaching the closing } and the returned value is used, it invokes invokes undefined behaviour.
Ref: Chapter §6.9.1, paragraph 12,
If the } that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined.
Related
Today I was experimenting with random C code and I found something that confused me. In the following program:
#include <stdio.h>
int f(int x)
{
if(x==2)
return 2;
else
{
printf("+");
f(x-1);
}
}
int main()
{
int n,i;
n = f(6);
printf("%d\n",n);
}
The output is quite expectedly ++++2, there is no confusion about the number of '+' because the number of recursive calls is 4. But my question is about the return value 2. In the function, a value is returned when the if(x==2) condition holds. Now when the function is being called with numbers other than 2, it will enter the else block. There is no explicit return statement in that block. But still it is returning a value. How is it allowed? How is the program deciding to return a number even when it is not explicitly told to do so? Is it that the program is simply returning the number it obtained from the recent function call? When a function is called, the caller maintains a stack. The return value is stored in a register. Is the function supposed to return the value stored in that register? Someone please explain it.
In case the } that terminates the function is reached, and the returned value is used in the caller, the behavior of the program is undefined. You cannot expected any reasoning for the value you got as return. In another run, it may return a completely different integer value, return the complete lyrics of your favorite song, or set your computer on fire. Nothing is guaranteed.
Quoting C11, chapter §6.9.1
If the } that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined.
#include<stdio.h>
int fact(int);
int main()
{
int a, b;
printf("enter a number : ");
scanf("%d",&a);
b=fact(a);
printf("\n%d",b);
}
int fact(int y )
{
int d=1;
for(int i = 1;i<=y;i++)
d*=i;
d= d>0 ? d : 0;
}
If I remove the last statement , O/P is a+1.
I have checked this with other functions and the function returns correct values if I use if statement or conditional operator.
I want to know why this happens.
Thank You.
6.9.1 Function definitions
...
12 If the } that terminates a function is reached, and the value of the function call is used by
the caller, the behavior is undefined.
Simply put, the behavior you're seeing is purely accidental. There's no good reason why you should get that particular result or any other.
Undefined means that the code is erroneous, but neither the compiler nor the runtime environment are required to handle it in any particular way. What's likely happening in your case is that the register used to return a value from a function is also being used to store the value of d, but that doesn't have to be true. If you change up the code, you may get a different result.
This question already has answers here:
unexpected output in C (recursion)
(3 answers)
Closed 4 years ago.
#include <stdio.h>
int main()
{
static int i = 5;
if (--i)
{
main();
printf("%d\n", i); // will this line executes ?
}
return 0;
}
Output:
0
0
0
0
does code below main(); printf statement instructions is placed to stack every time when main recursive calls happens and executed while terminated from this program?
i is reduced by successive calls to main until zero is reached.
Then printf is called for each level of recursion.
(Note that the behaviour of calling main from itself is well-defined although ill-advised in C, in C++ the behaviour is undefined.)
if (--i)
This will evaluate true the first time (--i == 4). The code recurses into main(). (Recursion: A function calling itself.)
As i is static, it will retain its value of 4 (as opposed to an automatic variable, which would be initialized to 5 again). The if (--i) in this second execution of main() will again be true (evaluating to 3), and will again call main() (for a third execution of the function).
The same for --i == 2 and --i == 1, for four executions of main() (including the first, non-recursive one) total that are evaluating the if condition to true.
The next recursion will evaluate the if condition to --i == 0, and thus false. Skipping the if clause, the function call will just return. i is zero at this point, and -- being static, i.e. only one persistent i for all instances of main() -- will remain at that value.
The main() call one level up the stack -- the one that evaluated --i == 1, then called main() and was waiting for it to return -- will now continue with the statement after the call to main(), and printf() the current value of i... which is 0.
The same happens three more times (for a total of four) until the top-most main() returns. You get four times the current value of i, which is 0.
Note that calling main() from your program is allowed in C, but not in C++. This is specifically for calling main() recursively; for other functions, it is allowed in either language.
(--i) will decrease the value of i to 4 when it is called for the first time and it will continue the decrement of i until (i==0) due to recursion.
Since you have declared the variable i with static keyword and hence a single memory is allocated to it and all the changes are reflected back to it
#include<stdio.h>
#int add(int n);
int main()
{
int n;
printf("Enter an positive integer: ");
scanf("%d",&n);
printf("Sum = %d",add(n));
return 0;
}
int add(int n)
{
if(n!=0)
return n+add(n-1); /* recursive call */
}
How will this code executed without having a base case like if(n==0){return 0;}?
Without a base case you are creating code with undefined behaviour. Your compiler will issue a warning saying that your function that returns int does not have a return statement. This does not mean that the function that called it won't look for a returned value which may or may not contain garbage.
You're going to run into problems here: add will only return a value if n != 0, so if n <= 0, you won't have a value returned, so when add calls itself with n-1 passed in, you'll eventually reach your base case that doesn't exist, and bad things will happen.
if(n==0){return 0;}
is the base case. The base case exists to get the recursion to stop. Without a base case you will just infinitely recurse until you possibly hit some kind of error. In your case it will start adding negative numbers.
From the C standards:
Flowing off the end of a function is equivalent to a return with no
value; this results in undefined behavior in a value-returning
function.
Your compiler may warn you:
not all control paths return a value
It's the same situation with this one.
This is calling convention and architecture dependent. The return value is the result of last expression evaluation, stored in the eax register. So when n==0, you function add() returns 0, but it's a result of undefined behavior.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is really happening in this code?
I have a code which includes a recursive function. I have wasted a lot of time on recursion, but i still couldn't get it, really:
#include<stdio.h>
count(int);
main(){
int x=10,z;
z=count(x);
}
count(int m){
if(m>0)
return count(m-1);
}
When count is called for the first time with argument 10, it fulfils the condition and the recursion starts. What happens really when a function calls itself? I dont get it. What does the statement return count(m-1) mean? Where does it tranfer the control?
The return value of the function count is undefined, because there is no default return if (m <= 0) is true.
C11, § 6.9.1 Function definitions
If the } that terminates a function is reached, and the value of the
function call is used by the caller, the behavior is undefined.
Besides, to understand how a recursive function works, you have to take a paper and try to execute the code by yourself (see also here).
You need count to return something when m <= 0. You should declare the return type of count and compile with -Wall so the compiler will help you find mistakes in your code.
recursion means that the function will call itself, mostly at the end of itself, if it's tail recursion.
So your count function checks that the input argument is > 0 and then if it is, it will call count(m-1). Now it starts at the top of count with m=9. It does the same thing, and then calls count with m=8, etc.
Until the end condition is reached, which should normally be explicitly catered for in your function, such as if (m == 0) return m; or some such thing. At that point the recursion ends and the function terminates.
Also, count should have a return type, such as int count (int m)
what does the statement return count(m-1) mean ? where does it tranfer the control?
That seems to be your only question.
it means that it is calling "count" with the value m-1. So if m was 10, then it is calling "count" with 9.
It is transferring the control recursively to the count method.
You also don't have a return for the every possible path in the "count" method.
What happens if m is <= 0?