Is it possible to force tail call optimization on GCC/Clang?
Clang is not doing any optimisations at all. There is an LLVM pass tailcallelim
which may do what you want (but it is not guaranteed). You can run it separately with opt
.
Clang 13 "musttail" attribute to force tail call optimization in tail recursive functions even if optimizations are disabled.
https://clang.llvm.org/docs/AttributeReference.html#musttail
usage:
int f(int x) {
...
__attribute__((musttail)) return f(x-1);
}
A meta answer:
There are some lessons it's useful to take over into C from functional languages: use small functions, use functions which don't mutate either globals or input arguments, don't be frightened of function pointers. But there's a limit to what you can reasonably do here, and relying on tail-call elimination ('tail-call optimization' isn't really the right term) is probably beyond what's useful. You can't force the compiler to use this strategy, and even if you could, the resulting C would be extremely unidiomatic, and hard to read for others, including your future self.
Use languages to their strengths. C is good for some things, so use it for those, in good C style. If you want different strengths, or if you want to use a functional style (excellent decision!), use a functional language.
I don't think it really enforces it, but you can use -foptimize-sibling-calls
when using gcc
. It's automatically enabled if you use -O2
, -O3
or -Os
.
In general, I'd advice against overusing recursion in C. If you really want to do fp, pick a functional language. There are cases where it is suitable, like quicksort, buf if you make a habit out of using recursion instead of loops, chances are pretty high that you will blow the stack.