Jan Mocks Flashcards
Recursion
When a subroutine calls itself within its own subroutine
A recursive subroutine should:
Contain a stopping condition (base case)
For any input value other than the stopping condition, the subroutine should call itself
The stopping condition should be reachable within a finite number of times
- without these characteristics a recursive subroutine may call itself indefinitely resulting in a stack overflow
Is recursion good
Recursion is not very memory efficient. Every time a recursive function calls itself the processor needs to remember where it was before it jumps to the new copy so it knows where to return later.
The processor also needs to remember the values of all the previous variables, as they are local to those copies of the recursive function- using stacks which takes up space in memory
Stack overflow
Recursive subroutines calls itself too many times before reaching its terminating condition you could run out of memory and cause the program to crash
When should you use recursion over iteration
Tree traversal algorithm
Performing a flood fill in a graphics application
Local variable accessibility
Single subroutine only
Local variable created
Declared inside a subroutine
Local variable destroyed
When the subroutine exits
Global variable accessibility
Entire program
Global variable created
Declared outside of a subroutine. Typically at the start of a program
Global variable destroyed
When the program ends
Local variable
Created when the subroutine is called
Global variable
Created when the program starts
Good program practice (g+l variables)
A system of passing in required values to the subroutine via parameters and returning values is considered safer and better programming practice
Why is overuse of global variables bad
Excessive, unnecessary use of global variables can make programs hard to test, debug and maintain