#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.
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.
I wrote a C program to use recursive functions to find the factorial of a number and the code is given below:
//program to find factorial of a number using a recursive function
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
int factorial(int a);
int main()
{
int num, fact;
printf("Enter a number: ");
scanf("%d", &num);
if(num<=0)
{
printf("The number cannot be zero/negative.");
exit(1);
}
fact=factorial(num);
printf("The factorial of the entered number is: %d", fact);
getch();
return 0;
}
int factorial(int a)
{
while(a>1)
return a*factorial(--a);
}
In the above code in 'while' loop if the input 'a'>1 then it should execute, but when i compile the program (using Dev C++ v.5.4.2) and give the input as 1, I get the factorial as 1. The program is the solution to the required problem, but i need to know what is actually happening in background...
Thank you in advance
int factorial(int a)
{
while(a>1)
return a*factorial(--a);
}
This function does not return anything if the condition in while loop is not true. Thus , invoking undefined behaviour (Maybe giving you correct output).
You should handle that case -
int factorial(int a)
{
if(a==1)return 1;
//while(a>1) // you use recursion then why using loop
return a*factorial(a-1);
}
In the case where a <= 1 your function does not have a return statement, even though it expects one. Which means you have a bug which will invoke undefined behavior: anything can happen, including: "seems to work ok", "weird output", the program crashes etc.
A half-decent compiler would warn you for this. For example GCC with warnings enabled:
warning: control reaches end of non-void function [-Wreturn-type]|
This is undefined behavior.
N1256 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.
To know what is actually happening in this specific situration, have your compiler output assembly code and read it, or use debugger suce as OllyDbg.
Your compiler seems to allow omission of return value. What happens is that your "factorial" function will not execute the while() loop, and after the while loop there is no return statement, so the return value will be undefined.
int factorial(int a)
{
while (a>1) // a is 1 so this will be false, and the loop will not execute
return a*factorial(--a);
return 1; // this value will be returned
}
Also, I suggest you review this code (looks like a school exercise to me). Currently, although it may work correctly, the code differs from how an experienced programmer would implement it.
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.
#include<stdio.h>
int GetPositiveInt(void);
int main(void)
{
int num = GetPositiveInt();
printf("%d",num);
return 0;
}
int GetPositiveInt(void)
{
int n;
do
{
printf("Enter a positive number : ");
scanf("%d",&n);
}while(n<=0);
}
The output is the value of n but I don't know how it is returned to num.
Does scanf() and printf() affect the return value of a function?
If I add a statement like printf("%d",7); after while then the output is 71,no idea how 1 comes.
This is my output. This is for reference only .
Text as requested :-
usr#usr:~/C_programs$ gcc -std=c99 return.c -o return
usr#usr:~/C_programs$ ./return
Enter a positive number : 45
45usr#usr:~/C_programs$ ./return
Enter a positive number : 89
89usr#usr:~/C_programs$
TL;DR Your code produces undeifined behavior.
You're missing a return statement in GetPositiveInt() function. Without having an explicit return statement to return a value, collecting the return value of the function call in the caller function and using that leads to undefined behaviour.
Ref: As per the C11 standard document, 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.
FWIW, only in case of main() , addition of return statement is not mandatory. From same document, chapter 5.1.2.2.3, for main() function
reaching the } that terminates the main function returns a value of 0.
In the following function:
int GetPositiveInt(void)
{
int n;
do
{
printf("Enter a positive number : ");
scanf("%d",&n);
}while(n<=0);
}
the function is expected to return an int value, whereas there is no return statement. You probably wanted to return the value of n. This can be achieved by adding the suitable return statement:
return n;
Like this:
int GetPositiveInt(void)
{
int n;
do
{
printf("Enter a positive number : ");
scanf("%d",&n);
}while(n<=0);
return n;
}
no idea how '1' comes.
Because you did not return anything in your method GetPositiveInt - and the behavior is undefined:
int GetPositiveInt(void)
{
int n;
do
{
printf("Enter a positive number : ");
scanf("%d",&n);
}while(n<=0);
return n; //<---Add this line
}
C99 6.9.1/12 "Function definitions" says:
If the } that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined.
It prints 0 for me.
As explained in the other answers, the lack of the return statement in a function that is declared to return something is signaled by the compiler with a warning but the generated code exposes undefined behaviour. This means the function can return any value, the compiler cannot guarantee anything about it.
You can think of the value returned by a function as a hidden local variable of that function. Since the return statement is missing, the hidden variable is not initialized and its value is whatever garbage data happened to be in the memory at the time when the function was called.
In practice, the return statement is translated into a processor instruction that copies the returned value into one of the general-purpose processor's registries (usually %eax on x86). The calling function (main() in your code) gets the values from that register and uses it.
Because your function GetPositiveInt() does not contain a return statement, the compiler skips generating the instruction that puts the correct value in %eax and the function completes its execution letting in %eax whatever value happened to be there as a result of earlier processing.
This is a case of undefined behaviour because you are missing the return statement.however I can explain why 1 is coming.
The printf function returns the number of characters printed by it.For example
printf("%d",printf("%d",7));
first printf prints 7 and returns 1 as number of characters printed. So output is 71.