r/learnprogramming • u/Temporary-Warthog250 • Apr 05 '22
Name one programming/comp sci concept you never understood and if you understand it, try to explain it to them
Name a programming concept such as virtual functions, pointers, certain algorithms, etc that you always had a hard time understanding and why.
Someone else who reads yours and does understand it, try to explain it to them to help them learn
1.6k
Upvotes
20
u/AlSweigart Author: ATBS Apr 05 '22
I just got done writing an entire book on recursion.
Recursion is tricky, but mostly it's just poorly taught. The main thing that instructors fail to talk about is the call stack. It's the invisible data structure that automatically handles where the execution should return as you call and return from functions.
Once you know that, and you can see that local variables are local to the function call and not just to the function, it becomes a bit easier to see how recursive functions work.
It's tricky though, because you can't point to the call stack in your source code. Without having that explicitly pointed out, recursion just seems like magic. But it isn't magical or somehow more powerful: *literally anything you can do with recursion you can do without recursion by using a loop and a stack. It's just that recursive algorithms use the (unstated, hidden) call stack as their stack.
(I always get people saying, "some things do require recursion" and, no, they don't require it. Here's a non-recursive Python implementation of the famously recursive Ackermann function, and it has the same output as the normal recursive one.)
It's fine to have difficulty with recursion though; recursion is overrated and often a terrible way to write code. The times when recursion is useful is for problems that involve a tree-like structure and some sort of backtracking (maze solving, tower of hanoi, etc). Otherwise, iterative code is much simpler and I think some programmers just use recursion because it makes them feel smart.