I'm trying to write a program in functional style with C as much as possible. I know fine compilers like GCC/Clang do tail call optimization silently, but it's not guaranteed. Is there any option to force tail call optimization on the compilers? (Of course when only it's called at the end of itself)
Some C compilers, such as gcc and clang, can perform tail call optimization (TCO).
Tail call optimisation isn't in the C++ standard. Apparently, some compilers, including MS Visual Studio and GCC, do provide tail call optimisation under certain circumstances (when optimisations are enabled, obviously).
This kind of function call is called a tail call, and languages like Haskell, Scala, and Scheme can avoid keeping around unnecessary stack frames in such calls. This is called tail call optimization (TCO) or tail call elimitation.
Tail call optimization is the specific use of tail calls in a function or subroutine that eliminate the need for additional stack frames. Tail call optimization can be part of efficient programming and the use of the values that subroutines return to a program to achieve more agile results or use fewer resources.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With