I’m not sure if this question has been asked before ( searched through SOF and couldn’t find an answer)
I wrote a LinkedList class and a function to reverse it.The function as follows,
struct LinkedList::element* LinkedList::recurrsiveReverseList(element* head){
element* tempList;
if(head->next == NULL){
return head;
}else{
tempList = recurrsiveReverseList(head->next);
head->next->next = head;
head->next = NULL;
return tempList;
}
}
here I am declaring a local pointer variable and making some changes to it and returning it back to the caller. In C++, when I declare a local variable inside a function the scope exists only inside the function. Now when I return the pointer from the function how does it work? I am able to understand the logic and get the result (luckily) but I am not able to completely understand the working here.
Can somebody clear my doubt?
The scope of
tempListterminates when you exit the function buttempListis a pointer to a block of memory whose scope does not terminate there because it’s been undoubtedly allocated bynew. Memory allocated in such a way is valid right up until the point youdeleteit, regardless of how many functions you go in to or out of.By passing the pointer back to the caller, it preserves said pointer elsewhere, where you can use it.
A simple example:
In the code above, the scope of
rvis limited to thefnfunction after it’s declared.The scope of
xis limited to themainfunction after it’s declared.However the memory allocated by
newcomes into existence withinfnand continues to exist after returning tomain. The address of said memory, initially stored inrv, is transferred toxby the assignment of thefnreturn value tox.