Recursive and inline functions in c++
Can anyone tell me the main difference between an 开发者_开发知识库inline function and recursive function?
These are unrelated concepts.
An function may be declared inline, which signals to the compiler that any calls to the function should be replaced by an implementation of the function directly at the point the call is made. It's vaguely like implementing some piece of logic as a macro, but it retains the clean semantics of a normal function call.
A recursive function is simply one that calls itself.
Note that the inline keyword is just a suggestion. The compiler is free to ignore it whenever it wants.
Also note that a recursive can also be declared inline. The compiler may, in principle, be able to inline a recursive function by transforming it into an iterative algorithm inside the calling function. However, recursion is usually one of the things that will make a compiler give up on inlining.
These are two very different concepts.
99% of programming languages allow recursive functions. A recursive function re-calls it's self to get something done. Most recursive functions can be rewritten as loops.
E.g. Simple recursive function.
int Factorial(int f)
{
if(f > 1)
return f * Factorial(f-1);
else
return 1;
}
An in-lined a function is a hint to the compiler that you don't want the processor to jump to this function, instead just include the op-codes for the function where ever it is used. This builds faster code for some calls one some architectures. Be aware that most modern compilers targeting non-embedded processors will choose to ignore your "inline" hints, and will choose what to inline itself.
Hope this helps, apologies if badly formatted, typed on my I-phone.
A recursive function is a function that calls itself.
An inlined function is a function, that is "inserted into another function", i.e. if you have an inlined function add(a,b)
, and you call it from a function func
, the compiler may be able to integrate the function body of add
into the body of func
so the arguments don't need to be pushed onto the stack.
精彩评论