I was just wondering when exactly a recursive function repeats itself.
Below is code from inheritance.c
from CS50's Lab 5:
person *create_family(int generations)
{
// TODO: Allocate memory for new person
person *p = malloc(sizeof(person))
// Generation with parent data
if (generations > 1)
{
// TODO: Recursively create blood type histories for parents
p->parents[0] = create_family(generations - 1);
p->parents[1] = create_family(generations - 1);
// TODO: Randomly assign child alleles based on parents
p->alleles = p->parents[0]->alleles[rand() % 2];
p->alleles = p->parents[1]->alleles[rand() % 2];
}
// Generation without parent data
else
{
// TODO: Set parent pointers to NULL
p->parents[0] = NULL;
p->parents[1] = NULL;
// TODO: Randomly assign alleles
p->alleles[0] = random_allele();
p->alleles[1] = random_allele();
}
// TODO: Return newly created person
return p;
}
generations
is set to 3
by default.
From what I put together, the recursion happens immediately at p->parents[0] = create_family(generations - 1);
create_family
is called repetitively at this point of the code until the condition generations > 1
is no longer true.
In which case, the latest call of create_family
is completed first, followed by the 2nd last call of create_family
, so on and so forth.
Is my understanding correct, or have I misunderstood where the recursion actually takes place?