The whole idea of variables existing foir various lengths of time is based in the concept of scope.
There are various kinds of scope but the one causing the problem is is called block scope. That is, the code between a pair of braces. The rule is any variable created between a pair of braces ceases to exist when the execution of the program passes beyond the closing brace.
In a function, all variables cease to exist when the function completes. This also includes the variables used as arguments. Remember, a
copy is created of a variable used as an argument to a function.
This is why returning the address of a variable inside a function never works.
In this code:
- int* MyFunction(args...)
-
{
-
int * ptr = new int;
-
return ptr;
-
}
ptr is a local variable and cannot be returned. Yet it appears to be returned. Like argument variables are copies of the variables actually used in the calling function, a returned variable is a
copy of the variable inside the function. Here the compiler makes a copy of ptr and returns the copy. The actual ptr ceases to exist after the closing brace.
So this is valid:
- int main()
-
{
-
int* ptr = MyFunction(args....);
-
}
The ptr in main() is not the ptr in MyFunction. Here the
copy of the return variable in the function is assigned to the ptr variable in main(). Then the compiler deletes the copy.
Various compilers implement the process differently, but the logical concept is always true.