About using recursion in C

When I injected the lexical analyzer into C, I found myself writing 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 implementing a 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, if only the case actually requires recursion (for example, a recursive descent parser or tree structure)

What i think so far

The benefits of recursion:

  • readable and elegant

Disadvantages:

  • quickly lead to a stack overflow (on my computer, this is about 1 million calls)
  • may be ineffective compared to the iterative version

Solutions:

  • use tail call optimization, and let the compiler convert my recursion into loops, but I find the callback code less readable.
  • Increase stack size for my program

Note

, , C.

+4
2

, , , , , , , "" (, ). , , .

- , - , *. , . , , , , , , , .

(, , , , ), , . , , .

* .

+2

. , . , , .

- ( - ) , , , [ , List_length]. .

. " " , , . ( , ), / .

, : unit test .

+2

All Articles