Cpp webinar doubt

at 35:00 how a is returning value it is pointer variable so it is actually returning address and it too gets destroyed than y b gets value of a this point is not clear to me.

1 Like

Hello @Divya_321

First thing is when we return a simple data type like int, string, char they are returned by value i.e, first the value is assigned to the variable in the returning function and then the local variable is destroyed.

Now in present scenario when both the variable ‘a’ and array were allocated space statically, ‘a’ had the address of the static array but it returned 0 while when it had the address of the dynamic array it returned the address of the array.
so why in the case 1 (when the array was also statically declared), ‘a’ returned 0. It should return the address of the local array

Ans- The compilers would have some kind of mechanism so as NOT to return the address of any local variable but the address of some dynamically allocated object can be returned.
So in second case the address is assigned to ‘b’ by value and then ‘a’ is destroyed.
While in first case compilers do NOT allow returning the address of local variable so 0 is returned.

Just for fun
If you want to know the address of the local variable of a function in another function, you can try this

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.