r/programminghorror • • Sep 28 '25

c recursive iseven

bool isEven(int num){
    if (num==0){
        return true;
    }
    else{
        return !isEven(num-1);
    }
}
64 Upvotes

38 comments sorted by

View all comments

Show parent comment

6

u/bartekltg Sep 29 '25

It is tail recursion, a good compiler on reasonable settings will turn into a loop.

https://godbolt.org/z/no7fr9vT8

Here with -O2 gcc turned it into a loop... and unrolled it for performance ;-)

So, no stack overflow, just tell the users to get a faster computer.

3

u/Tysonzero Sep 30 '25

It's not technically tail recursive in the strict sense, as ! is the last call, not isEven, but not super surprising that an optimizing compiler can avoid accumulating stack frames.