In C ++, inline modifiers are introduced to solve the problem that frequently called small functions consume a lot of stack space or stack memory.
Many people may not understand what stack space is.Stack space refers to placementProgramThe local data is the memory space of the data in the function.In the system, the stack space isLimited If a large number of applications are frequently used, program errors may occur due to insufficient stack space. The final result of the endless recursive call of functions is the depletion of stack memory space.
Here is an example:
# Include <iostream>
# Include < String >
Using Namespace STD;
Inline String Dbtest ( Int A );// The original function declaration is inline: Inline Function
Void Main ()
{
For ( Int I = 1 ; I <= 10 ; I ++)
{
Cout <I < " : " <Dbtest (I) <Endl;
}
Cin.Get ();
}
String Dbtest ( Int A) // You don't need to use inline again here. Of course, when you add inline, it won't make any mistakes.
{
Return (A % 2 > 0 )? " Odd " : " Even " ;
}
The above example shows the usage of standard inline functions. We cannot see the benefits of inline modification, in fact, the internal work is to replace (I % 2> 0) Where dbtest (I) is called within each for loop )? "Odd": "even", this avoids the consumption caused by frequent calls to functions to repeat stack memory.
Many people may ask that since inline is so good, it is better to declare all the so-called functions as inline. Well, you should pay attention to this question, the use of inline is limited,Inline is only applicable to function bodies.CodeSimple functions cannot contain complex structure control statements such as while switch, and inline functions cannot be directly recursive functions (they also call their own functions internally ),(Note: the expansion of the recursive call stack is not as simple as a loop. For example, the number of recursive layers may be unknown during compilation. Most compilers do not support inline recursive functions)
Speaking of this, we have to talk aboutC Language# Define statement widely used in, yesDefine can also do the work of inline, but define can produce side effects, especially errors caused by different types of parameters.It can be seen that inline is more restrictive and allows the compiler to check for more error features. Define is not recommended in C ++.