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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With