#include<stdio.h>
int add(int,int);
int main()
{
int a;
a=add(5,7);
printf("%d",a);
}
int add(int x,int y)
{
x=x+y;
return(x);
}
Last night I got a doubt on return statement. See x is an auto variable defined inside the add function and as ANSI said an auto variable exists and has its lifetime only inside the function but here the return statement can make the variable a to exist even outside the function. Where does it store the value ? Stack or heap ?
Neither on the stack nor on the heap.
At least in the x86 architecture, the return value of functions is usually copied to the
eaxregister, so it persists outside of the function. This is one of the reasons why you can’t return an array but merely a pointer to it.You can, however, return structs and other larger variables by value, in which case the compiler does some tricks by using the stack and additional registers such as
edx.