I'm confused regrading the return
of a local variable: the variable, its address and returning address using pointers.
First:
#include <stdio.h>
int returner(void);
int main(void)
{
printf("The value I got is = %d\n", returner());
return 0;
}
int returner(void)
{
int a = 10;
return a;
}
Output:
The value I got is = 10
The local variable is returned although it should go out of scope after the function returns, how does that work?
Second:
#include <stdio.h>
int *returner(void);
int main(void)
{
int *pointer = returner();
printf("The value I got is = %d\n", *pointer);
return 0;
}
int *returner(void)
{
int a = 10;
return &a;
}
Output:
Test.c: In function 'returner':
Test.c:15:12: warning: function returns address of local variable [-Wreturn-local-addr]
15 | return &a;
Why is the address is not returned, although the value is returned as in First sample?
Third:
#include <stdio.h>
int *returner(void);
int main(void)
{
int *pointer = returner();
printf("The value I got is = %d\n", *pointer);
return 0;
}
int *returner(void)
{
int a = 10;
int *ptr = &a;
return ptr;
}
Output:
The value I got is = 10
Now, how is this method returning the address of the local variable and also prints its correct value, although the variable should go out of scope / be destroyed after the function returns?
Please explain the three cases that how the methods are working.