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
        // 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?

1 Answer 1


Congratulations. You have interpreted recursive functions exactly correct.

  • Read the last line of the question. Then read the entire question. They asked if they got it right and they explained it exactly as I would explain it! So what's the problem???? How would you explain it differently????
    – Cliff B
    Commented May 5, 2021 at 18:03
  • @Vsjain this answers the question that was posed.
    – curiouskiwi
    Commented May 5, 2021 at 23:12
  • @CliffB Thank you for the validation! There was perhaps a comment you were replying to that got deleted, I'm guessing he/she was expecting a detailed answer. As yourself and curiouskiwi have pointed out, I was just asking if the way I explained it was correct. So this answer my question! Commented May 6, 2021 at 4:36
  • You're welcome! ;-)
    – Cliff B
    Commented May 6, 2021 at 19:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .