Q:

Using pointer as return value in function in c

Here is my code:
#include <stdio.h>
//returning a pointer
int *fun()
{
    int i = 10;
    //printf ("%u\n",i);
    //printf ("%u\n",&i);
    return &i;
}
int main()
{
    int *p;
    p = fun();
    printf ("p = %u\n", p);
    printf ("i = %u \n",*p);
    return 0;
}

If I remove the comments in the function fun, then the second printf in main shows 10 as the output.  otherwise it shows a garbage value.  any idea? 

A:

Without the commented lines i is never used.  So depending on your optimizer, i may never even be allocated.  When you add printf within the function, the variable is now used so  the compiler allocates memory for i on the stack frame (which happens to have not been reclaimed at the point your second set of printfs occurs).   Of course, you cannot depend on when that memory will be reclaimed- but the next function call that occurs is very likely to overwrite the fun() stack frame. 
If you set your compiler to disable code optimization you may have a different result.   Or you can try setting the variable to volatile which tells the compiler that it doesn't know about all uses of the variable and so allocate it even if the optimizer says it's not needed (which won't stop your variable's memory from being deallocated after you leave the function, it'll just force the allocation in the first place). 
As a side note this issue can come up in embedded systems where you have a pointer to a hardware register that triggers hardware actions when set (for instance you might have hardware registers that control a robots arm motion).   If you don't declare the pointer to that register volatile then the compiler may optimize away your assignment thinking it's never used. 