While implementing a lexical analyzer in C, I found myself writing a recursive code:
// Return a List of Tokens
List Lexer_run(const char* input) {
if(input[0] == '\0') {
return new_List();
} else {
// ... Find Token and possibly advance in input for a few characters
return List_add(Lexer_run(nextInput), newToken);
}
Consider another example in an implementation of linked list
List_length(List* this) {
if(!this) {
return 0;
} else {
return 1 + List_length(this->next);
}
}
I am wondering if I can always use such recursive code in C or if I should avoid it unless the case really requires recursion (for example recursive descent parser or a tree structure)
What I think so far
Advantages of recursion:
- readable and elegant
Drawbacks:
- will rapidly cause a stack overflow (in my computer it's around 1'000'000 calls)
- can be inefficient comparing to an iterative version
Solutions:
- use tail-call optimization and let the compiler transform my recursion into loops but I find tail-call code to be less readable.
- Increase stack size for my program
Note
My question is not specifically about my examples but rather a general question if one should use recursion in C.
main()). You are also encouraged to write recursive code if it's more readable than its iterative counterpart. Yes, recursion can be slower. Yes, it can cause stack overflow. And that doesn't always matter -- don't optimize prematurely.