c++ inline function inline usage instance

  • 2020-06-19 11:18:39
  • OfStack

Problem description: Member functions in a class are inlined by default, so it would be nice if the function definition was given within the class at the time of the class definition. If a member function is not defined in a class and you want to inline that function, add inline to the class, otherwise it will not be considered inline. inline for inline functions is appended to the function, not to the declaration.


class A
{
  public:void Foo(int x, int y) { } //  Automatically become inline 
}
// Correct writing: 
//  The header file 
class A
{
  public:
  void Foo(int x, int y);
}
//  The definition file 
inline void A::Foo(int x, int y){} 

// Error: 
inline void Foo(int x, int y); // inline  Is placed only with function declarations 1 since 
void Foo(int x, int y){}

1. Inline functions: In order to solve the problem that 1 frequently called small functions consume a large amount of stack space (stack memory), inline modifier is specially introduced to represent inline functions.

Example:


#include <stdio.h>
// The function is defined as inline namely : Inline function 
inline char* dbtest(int a) {
  return (i % 2 > 0) ? " p. " : " accidentally ";
} 
 
int main()
{
  int i = 0;
  for (i=1; i < 100; i++) {
    printf("i:%d   parity :%s /n", i, dbtest(i));  
  }
}

Inline functions are added to a program by substitution at compile time.

2. Restrictions on the use of inline functions:

The use of inline is limited. inline is only suitable for the use of cul-de-sacs with simple code in the cul-de-sacs body, and cannot contain complex structural control statements such as while and switch, and cannot inline functions themselves and cannot be direct recursive functions (that is, call their own functions internally).

Inline functions are not suitable for long code with internal loops.

3. Inline function is just a suggestion to the compiler, the concrete implementation depends on the compiler thinks the function complex is not complex.

4. Inline functions are best in a header file.

The above is the introduction of all the knowledge content, thank you for your learning and this site support.


Related articles: