Monday, March 25, 2013
On tail call optimization in certain C compilers
- From
- Mark Grosberg <XXXXXXXXXXXXXXXXX>
- To
- Sean Conner <sean@conman.org>
- Subject
- Tail calls.
- Date
- Sun, 24 Mar 2013 12:35:18 PM -0500
But here, I can't rely on the C compiler to optimize tail calls (GCC can, but only with certain options; I don't know about the Solaris C compiler). I could have the routines return the next function to call and use a loop:
I haven't verified it but it probably does. It's a pretty easy optimization (compared to what compilers do today) so I'd be surprised if the Sun C compiler doesn't handle this. At least for C code (C++ exceptions can throw some wrinkles in this in some cases).
-MYG
I decided to check. And yes, the
Solaris C compiler does support tail call optimizations. So I figured I
would play around with this a bit, both under gcc
and the
Solaris C compiler.
Final results: gcc
and the Solaris C compiler both support
tail call optimizations (some restrictions apply; void where prohibited;
your mileage may vary; results presented are not typical and yours might
vary; use only as directed; this program is distributed in the hope that it
will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE; do not taunt Happy
Fun Ball).
First off, the number of parameters must match among the functions; the types don't appear to matter that much, just the number. Second, the number (or size) of locally defined variables also matters. I'm not sure what the upper size (or number) for variables is (and it may differ between the two compilers) but it does appear to be a factor. Third, the only safe way to determine if tail call optimizations are being performed is to check the assembly code and check for calls (or, just run it and see if it crashes after a period of time).
So I can, kind of, assume tail call optimization in C code. It'll be something to keep in mind.