There is a part in your program's memory called the call stack. It grows with every function call. Because these functions would call each other endlessly, your call stack would likewise grow endlessly; funnily enough though, memory is limited, hence at some point your call stack cannot grow anymore and your program will crash
In programming there’s a way of storing data called a stack. A stack is literally a stack. You can think of a stack of papers. Every time you add a paper, you add it to the top. When you remove a paper (pop) it always has to be the one on top. It operates on last in first out principles.
When I call a function, the computer needs to remember where it was, and the arguments passed to the function. If I call isodd(n) it needs to remember what is calling isodd, and the number passed to it. If I then call iseven, it needs to remember how to get back to isodd.
Now imagine we did that infinitely. Computers have a limited space to store information, so eventually the stack gets so big it begins to overflow. Since papers are never removed, we will eventually hit a ceiling.
There is no input for which either of these methods will not call the other, meaning they must call each other infinitely in an alternating pattern
since the call isn't the last thing either of them would do before returning, the computer has to store the state of the current method before entering the next, and this takes up memory
Together, these mean that any input into either of these methods would attempt to consume an infinite amount of memory, except since there isn't an infinite amount of memory to consume, it'll just be stopped when it tries to consume any more than it's allowed.
Don't even need to know about the stack to understand why this doesn't work.
Just think through the steps logically, let's say you run isOdd(1) well in the if statement we need to call isEven(1) and then negate it (and if that's false we would evaluate the other side of the or operator (||).
Ok, well if we call isEven(1), we need to again evaluate the first statement, which is again an if statement. The first part of that if statement is to call isOdd(1) and negate it... Annnd we're back we're back in the same position where we started.
So you can see we have an infinite loop that will never end! (Ignoring the stack completely.)
View all comments
Show parent comment
32
u/Minimum_Session_4039 Mar 03 '26
Am new to programming, why?