Can someone please explain the following function ?
void printNthFromLast(struct node* head, int n)
{
static int i = 0;
if(head == NULL)
return;
printNthFromLast(head->next, n);
if(++i == n)
printf("%d", head->data);
}
I just want to know how order of execution of statements occur in recursion i.e given recursive call is before the second if condition , so will the second if condition be checked ?
Yes, the second
if
condition will be checked, after the recursive call returns. And it will return, provided the recursion terminates by reaching the end of the linked list. This concept is essential to understanding recursion. Most particularly, you must understand that each function call, including recursive ones, executes in its own context, and upon return control resumes immediately after the call. It's associated with the flow of execution, not with the function that is called -- you don't lose your place by calling a function recursively.