Recursion in C with function type return

This is a quick question, I did a search, but could not find anything that answered my question.

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

For instance:

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

Do I need to put the return keyword before a function call? I know that if a function returns something, for example, it searches for something in LL, it will need a return statement.

+4
source share
8 answers

No, you do not need it.

Long answer : Your recursive function is executed like any other, and if there is no recursive call, it just stops. You do not need an explicit refund. You can use it if you want to exit the function prematurely.

+9
source

In this case, there is no need for a return , but only because the function does nothing after a recursive call.

If you 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 will need to insert a return; after calling addToLL() , if you do not want someOtherCode() called after addToLL() returns.

+4
source

Returned values ​​from functions are not a prerequisite for recursion - in any language. So no.

0
source

This is more a style issue. Some people think that stopping the void function without the return faux-pas keyword is different for others. However, this is really not recursion.

0
source

When your function ends, it returns implicitly, so there is no need to call the return statement.

[Add Value] When functions are added back to the program, the functions of local variables and arguments are deleted, and the return values ​​become available to the calling function, and execution resumes at the calling position.
When the void functions are returned, they simply clear the arguments and local variables, and there is no need to worry about moving the returned values ​​to the right place.

0
source

No need for return type.

A recursive function is still useful without a return type, because it can, for example, print values, compute things by a pointer parameter, or do many other things.

0
source

I believe that your sample code is a good example of a recursive function than can be easily converted to a loop, creating less load on the stack when working in a very long linked list.

 void addToLL(structA_ptr new, structA_ptr cur) { while (cur->next) cur = cur->next; cur->next = new; } 
0
source

In a function with a void return type, the only reason for using the explicit return is that you want to exit the function prematurely.

0
source

All Articles