Say I have a simple function:
int all_true(int* bools, int len) { if (len < 1) return TRUE; return *bools && all_true(bools+1, len-1); }
This function can be rewritten in a more understandable tail recursive style as follows:
int all_true(int* bools, int len) { if (len < 1) return TRUE; if (!*bools) return FALSE; return all_true(bools+1, len-1); }
Logically, there is no zero difference between them; if bools contains only TRUE or FALSE (reasonably defined), they do the same.
My question is: if the compiler is smart enough to optimize the second as a tail recursive call, is it reasonable to expect it to optimize the first in the same way, given that "& &" are short circuits? Obviously, if the operator were used without a short circuit, this would not be tail recursion, because both expressions would be evaluated before the operator is applied, but I am curious about the case with a short circuit.
(Before I get a stream of comments telling me that C compilers usually donโt optimize tail recursive calls: consider this as a general question about optimizing tail recursive calls with short circuit operators, regardless of language. 'Iโm happy to rewrite this in Scheme, Haskell, OCaml, F #, Python, or what the hell else if you don't understand C.)
source share