I read recently several recursive functions which were declared static.
Does adding static in front of functions declarations help GCC to optimize tail-recursive function? Is this mandatory to get optimizations?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I don’t see any reason why a function being
staticshould help the compiler optimize recursive calls in particular.Immediately, it sounds more likely that the recursive functions you have seen were simply internal to the compilation unit. A recursive function will often need a richer interface than one wants to expose to the rest of the program — for example there might be extra parameters that are only used by the recursive calls, or the return value from a general call may need to be adjusted in order to fit with the abstraction one wants to present to the rest of the code. Therefore it is usual to write a wrapper function that sets default values for the extra parameters and in general adjusts the interface of the recursive function to something nice that makes sense externally.
Now since the recursive function is only called by itself and the wrapper function, it is natural to declare it
static— not because of the recursion itself, but in order to prevent polluting the global namespace with it. It is also possible that the compiler can use more efficient calling conventions (adapted to that particular function body) for static functions, because it knows all of the call sites and does not have to follow an ABI that will let separately compiled code call it.