a. When does the life-time of n (object of type int) start?
b. When does it end?
c. The function returns the address of an int; does the object at that address exist after the function returns?
a .when calling foo(1) , the int n gets integer 1 assigned DIRECTLY to it ( I guess no need to copy "1" here , correct me if I'm wrong)
b,c. lifetime ends after ";" of the return statement , thus we give a copy of address of the local n variable ( which its value will be garbage).
Nevertheless I still don't get it. I expected to receive some garbage value but not 2 times "2"
> thus we give a copy of address of the local n variable ( which its value will be garbage).
We can talk about the 'value' of an int if an only if the int in question exists. n had a value which it held till the end of its life-time; there is no int to hold that old value once the lifetime of n is over.
> I expected to receive some garbage value but not 2 times "2"
What you have got is undefined behavior.
Or talking in terms of garbage values, 2 2 is one of the many possible values that garbage could have.
But this kind of undefined beahviour seems a little bit strange to me , you can try messing with the values in the parameters of the called functions , you'll get "nice" output.
Yes, getting a "nice", repeatable output from undefined behaviour with a particular C++ implementation (and a particular combination of compiler options) is quite possible.
Permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message)
However, that does not make the code correct; it is not behaviour that we should be depending on.