Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursion in C function type with return

Tags:

c

recursion

This is a quick question, I did a search but couldn't find anything that answered my question.

When doing a recursive function in C do you need to have a return even when using a void function?

Eg:

    void addToLL(structA_ptr new, structA_ptr cur) {
        if (cur->next == NULL) {
             cur->next = new;
        } else {
             addToLL(new, cur->next);
        }
    }

Would I need to put a return keyword before the call to the function? I know that if the function would return something, like searching for something in the LL it would need a return statement.

like image 517
jumm Avatar asked Dec 14 '22 01:12

jumm


2 Answers

No, you don't need it.

Long answer: Your recursive function is executed like any other and if doesn't encounter a recursive call, it is simply terminated. You don't need an explicit return. You can use if you want to exit the function prematurely.

like image 133
Dario Avatar answered Dec 24 '22 22:12

Dario


There's no need for a return statement in this case, but only because the function doesn't do anything after the recursive call.

If you'd had this:

void addToLL(structA_ptr new, structA_ptr cur) {
    if (cur->next == NULL) {
         cur->next = new;
    } else {
         addToLL(new, cur->next);
    }

    someOtherCode();
}

then you'd need to insert a return; statement after the call to addToLL() if you didn't want someOtherCode() to be called after addToLL() returned.

like image 26
RichieHindle Avatar answered Dec 24 '22 22:12

RichieHindle