#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.
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:
What is the proper declaration of main in C++?
(5 answers)
In the main function of a C++ program, what does `return 0` do and mean? [duplicate]
(12 answers)
Closed 8 years ago.
I'm reading Programming in C by Brian Kernighnan an Dennis Ritchie in that(pg.25 bottom)
Here the author quotes:
The value that power computes is returned to main by the return statement. Any expression may follow return: return expression ;
But in the code he provided above:
#include <stdio.h>
int power(int m , int n);
main()
{
int i;
for (i = 0; i < 10; ++i)
printf ( " %d \t %d \t %d \n ", i, power( 2 , i), power( -3 , i));
return 0;//no. 1
}
int power(int m , int n)
{
int i, p ;
p = 1;
for (i = 1; i <= n; ++i)
p = p * m;
return p; //no. 2
}
Here I understood why he used 2. return p; in function power (i.e to get the value of p) but why does he use 1. return 0; ??
I tried removing the line return 0; And it still worked as I had thought, is there something I'm missing??
[UPDATE]
I'm sorry for not including this before but I already knew this much:
quoted in the book:
You may have noticed that there is a return statement at the end of
main. Since main is a function like any other, it may return a value
to its caller, which is in effect the environment in which the program
was executed. Typi- cally, a return value of zero implies normal
termination; non-zero values signal unusual or erroneous termination
conditions. In the interests of simplicity, we have omitted return
statements from our main functions up to this point, but we will
include them hereafter, as a reminder that programs should return
status to their environment.
Thanks to #Pascal I was able to understand the difference in both the return p; and return 0;
However my intention was never to know what return 0; was but why return was used also to know the difference between both the return statment......
In a function other than the entry point of the program, return e; indicates the result that will be sent to the caller.
A return i; statement in the main() function is a way instead for the program to communicate an exit code to the operating system. In POSIX, return 0; indicates success.
The return 0; at the end of function main() is so perfunctory that in C99, it was made optional. The } ending function main() implicitly behaves like return 0; according to the standard:
5.1.2.2.3 Program termination
1 If the return type of the main function is a type compatible with int, a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument; reaching the } that terminates the main function returns a value of 0[…]
However, in C90, there is no such exception, and it is technically undefined behavior to have an int-returning function such as main() reach the final } without a return statement. The worst that seems to happen in practice is that the program returns with an indeterminate value in the register or stack slot reserved for function results, so that the Operating System may think that the program failed when it actually succeeded.
main()'s return code is conventionally a way for programs to give the operating system an indication on whether they completed successfully or no. Conventionally a return value of zero means success, while other values are used to indicate errors.
OS's like UNIX/Linux and Windows provide ways to check such return code; in sh or bash the $? holds the return code of the last command executed, in Windows' cmd you can obtain it as %ERRORLEVEL%.
The main function of every C program should return 0 if the program worked correctly. It's a convention which you should always follow.
According to the ISO/IEC C++ Standard (14882), section 3.6.1 states that the function main should have one of the two signatures:
int main(void) { .... }
or
int main(int argc, char** argv) { .... }
Most compilers accept variants of this, such as just main() { .... } for backwards comparability, such as your example code. The return at the end of main is the value that is returned to the calling environment (typically the command shell) and it can be used to represent successful completion of the program (by return 0), or return an error code to the calling environment in case of program error.
If you leave the return off at the end of main, a return 0; is assumed.
#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.