Returning a local variable confusion in C

2020-02-13 06:35发布

问题:

Recently I read a thread on stackoverflow that returning a local variable must be avoided whether its a pointer type or a normal variable. I saw an example in my C book and it was returning a local variable, so I thought to try it again

#include <stdio.h>
int func(int a, int b)
{
    int d, e, f;
    d = a;
    e = b;
    f = d+e;
    return f;
}
int main(void)
{
    int c = func(1, 2);
    printf("hello\n");//I put this printf in between
    printf("c = %d\n", c);//here c should be overwritten
    return 0;
}

In that thread it was said, that if I put anything between function call and accessing that variable, I will miss the value.

I am able to access the local variable whatever I do, yet I recall I wrote an example according to that thread and was showing same behaviour as told.

What am I missing?

回答1:

The unnamed thread you mentioned has mislead you.

In your example, func() is returning an integer. Returning an integer is always safe, regardless of where it came from.

Values (int, char, double) are never shared. Each time you pass/return them, a copy of that value is passed/returned, so it is safe.

Pointers (int*, char*, double*) can share the memory location they are pointing at. Passing/returning them can be dangerous, because the value at that memory location will change over time. You have to be careful with pointers.