r/C_Programming • u/avestronics • Jul 01 '26
Question Is it bad to use recursive stuff in C
Whenever I'm building anything in C, I try to create some structures to store data. For example I'm building a text editor now and the file browser needs a way to store entries in a given directory. So I came up with this.
typedef enum{
DIRECTORY_ENTRY,
FILE_ENTRY,
END_ENTRY,
OTHER_ENTRY
}entryType;
typedef struct fileBrowserEntry fileBrowserEntry;
struct fileBrowserEntry{
char * name;
entryType type;
bool isExpanded;
fileBrowserEntry * downDirectory;
fileBrowserEntry * upDirectory;
};The last element in an array of fileBrowserEntry has the type==END_ENTRY so I can loop through the contents. The issue is when I want to free a deeply nested structure like this I have to take care of these:
* The current directory might have a reference in the up directory so I have to make it NULL first.
* Every downDirectory might have its own down directories so we should go as deep as we can recursively.
Every C project I make has something similar to this where I have a recursive struct. Is this a bad pattern? If yes what are the alternatives?
55
u/ironykarl Jul 01 '26
IMO, it's a perfectly normal pattern in C, and there's no reason not to use it
4
u/didntplaymysummercar Jul 01 '26
Yeah, C requires manual memory management so here you are. Only bit of your code some might object to is no const on the name and that downDirectory seems like a pointer, not an array. Neither name nor comment signifies it's an array plus upDirectiry is a single pointer yet named in similar scheme. Some (not me) might dislike using a sentinel instead of explicit length (or both) too.
34
u/PlentyfulFish Jul 01 '26
Recursion I believe only really applies to functions. Structures that hold pointers to other instances of that structure form linked lists, graphs and trees and there is nothing wrong with them at all, they are widely used.
10
u/bobotheboinger Jul 01 '26
This looks like most tree based structures. Totally normal. If you look at any tree based algorithms you can find good examples of functions to parse these for most normal operations (add, remove, move, swap, etc)
6
u/WittyStick Jul 01 '26 edited Jul 01 '26
Recursive data structures are completely normal, there's nothing inherently bad about them, particularly for sequential or tree-like data structures. Alternatives exist, and may or may not be suitable - there's no one "right" way to do it.
For directories, although they look like a tree - if you consider the possibility of symlinks or hardlinks, then you need a directed graph, which may have cycles. The problem becomes more complicated, and is one of the more difficult problems when it comes to managing resources - we need to use something like "weak" pointers, garbage collection or some other strategy to prevent memory leaks or double-frees, and we need cycle detection to prevent indefinitely traversing through the same edges.
A common alternative for graphs is to maintain separate "node" and "edge" lists, and index into them by ID. For example, a directed edge would contain
source_nodeandtarget_node, which could be the indices into an array of nodes, and the nodes could contain a list of edge IDs, being the indices into an array of edges, rather than having direct pointers.4
u/This_Growth2898 Jul 01 '26
It's a linked list (or a tree, depending on what "up" and "down" mean), and it's an absolutely normal way to store complex structures in C. You just need to read something on data structures to avoid reinventing a wheel.
1
u/genafcvpxyr31 Jul 01 '26
When you mention "array of fileBrowserEntry" do you mean a pointer that points to the beginning of an array lying in heap memory?
This is probably a b-tree type data structure, often used in file-systems. Not the easiest to program, but they're efficient.
3
u/UnhappySort5871 Jul 01 '26
The one thing you need to watch out for with deeply nested structures is that operations on them don't abuse the stack too much. If your destructor is recursive, and your nesting is deep enough, will you get a stack overflow?
2
u/ActiveTelevision5443 Jul 01 '26
Yeah. Perfectly fine. I see these all the time. Linked lists and linked trees are a common and often neccessary thing to have.
2
u/Dusty_Coder Jul 01 '26
Just always be aware that the simplified version of most graph algorithms assume the graph is a tree and may not operate as expected when it isnt (infinite looping, etc)
I suspect that feeling you get, that there must be a better way, is because of how imperfect it is.
Dont confuse imperfect with a lack of utility.
There are lots of places where its OK to fail badly on unexpected inputs.
To ensure you are dealing with a tree, you need an abstraction on top. Abstractions have costs.
2
u/Doug2825 Jul 01 '26
If you need to recurse to many layers eventually you will have a stack overflow but that is unlikely for a file path.
In general if you see something that looks like it's a good candidate for recursion; implement it as recursion now, then convert it to a loop later if you run into stack issues or are really trying to optimize later.
2
u/MattR59 Jul 02 '26
I have had many people tell me that you should never use recursion. But in my career (retired now) I have made several recursive modules that worked very well and were small in size. When making a recursive module in an embedded system you need to monitor stack use closely.
2
u/TheThiefMaster Jul 01 '26
Tree structures (including a directory tree) are about the only sane use case for recursion in C. You're fine.
1
u/RevolutionaryRush717 Jul 01 '26
Recursive data structures are common, e.g., linked lists, trees, graphs, etc.
In C they must be defined using pointers.
They may be traversed recursively or iteratively.
Some C compilers offer some tail call optimization, but it is not guaranteed by the language or any compiler.
So a tail recursion might use n or 1 stack frames.
TL;DR: recursive data structures are very common in C.
Recursive functions are possible in C.
Tail recursion is possible in C.
TCO is compiler-dependent and not guranteed by the language.
1
u/_abscessedwound Jul 01 '26
Having a tree structure doesn’t necessitate recursion, depending on what you’re doing. BFS and DFS can (and I’d argue should) be written as iterative algorithms.
But yeah, cleaning up linked and nested structures like this one is tedious in straight C.
1
u/Physical_Dare8553 Jul 01 '26
of course it's fine. this is how strings work in c, but a bit more complex
1
u/ern0plus4 Jul 01 '26
No one thinks about stack.
You might check nesting depth, especially where it's determined by user input, e.g. directories, avoid stack overflov.
1
u/ReallyEvilRob Jul 01 '26
Recursion is very elegant design. Just keep stack variables to a minimum. If you're using large structures, consider allocating them on the heap.
1
u/8d8n4mbo28026ulk Jul 01 '26
No, but you'll be put on the naughty list.
1
u/Linguistic-mystic Jul 02 '26
Recursion is bad design and you'd do well to keep it to a minimum.
I'm sick of, for example, DBeaver and DataGrip crashing on lengthy SQL queries because their parsers use recursion.
1
u/FemaleMishap Jul 02 '26
Tail recursion is fun. Just remember your memory management.
1
u/SimoneMicu Jul 02 '26
This is not recursive, is a double linked list struct, you just hold reference of the previous and next in navigation.
Probably a more fast approach, if is used in a DFS navigation is to use an array (if dynamic search for `kvec.h` implementation of dynamic array) so you will know entry 0 is the root, each next entry is the next searched and previous entry is the parent (this consent to strip out the two pointer reference ONLY if you navigate first by deepness but lose other feature who you would find important).
A better approach for directory navigation should be a n-tree (since each directory have more then one child directory) or a rose tree (instead of an array of reference to children, each node/directoryBrowser store prev and next sibling and first and last children)
I have some implementations you could find useful in a livrary format (you can pick up only required header and source, is licensed completely public domain).
https://codeberg.org/SMicucci/libcaffeine.git
1
u/KirkHawley Jul 03 '26
Recursion is for programmers who haven't blown enough stacks yet.
1
u/Key_River7180 Jul 03 '26
Nothing bad, this is a very used pattern (consult the linked list!)