The answer is that yes, it is possible, but the compiler is not required to do this. Regardless of whether it works or not, a lot depends on the function, the compiler and the chosen optimization level. If you are concerned about this function for a particular function, look at the assembly created by a particular compiler at a certain level of optimization.
To be more specific, GCC (at least the version of Apple using LLVM as the backend) will generate tail-optimized code for at least some functions that return void at the optimization level of -O1 or better.
Some test codes:
void fillarray(int val, int* curr, int* end) { if (curr==end) return; *curr = val; fillarray(val,curr+1,end); }
With minimal optimization ( -O1 ), compiling to assembly ( gcc -O1 -S test.c ) creates a convenient optimized tail function:
_fillarray: pushq %rbp movq %rsp, %rbp
(Note: I edited some unnecessary labels and alignment instructions that hide the assembly structure).
In addition, when optimization is disabled ( -O0 ), the resulting code is recursive (not optimized with a callback).
source share