3 ms·
A contrived example: https://godbolt.org/z/17T5MzvGY https://godbolt.org/z/17T5MzvGY The compiler is able to optimize the function calls in the return statemen
by ufo 4y ago
A contrived example: https://godbolt.org/z/17T5MzvGY https://godbolt.org/z/17T5MzvGY
The compiler is able to optimize the function calls in the return statement. Note how the calls are compiled into a jmp instruction, instead of a call instruction. This means that it doesn't need a new stack frame for each call. Even if the "x" is very big, it won't blow the stack.
The most basic application of tail call optimization is when you optimize a recursive function. It essentially turns the recursion into a loop. In fact, is how you write loops in certain functional languages. But TCO is not jut for that. It can also be used when one function calls a different function, like in the first example I linked. In this case the gotos can model any state machine, not just a self loop.