C++ inline function inline


C++ inline functions are usually used with classes. If a function is inlined, then at compile time, the compiler places a copy of the function's code in every place where the function is called.

Any modification to an inline function requires recompiling all clients of the function, because the compiler needs to replace all the code once again, otherwise the old function will continue to be used.

If you want to define a function as an inline function, you need to place the keyword inline before the function name, and you need to define the function before calling the function. The compiler ignores the inline qualifier if the function is defined on more than one line.

Functions defined in a class definition are inline functions, even if the inline specifier is not used .

Here is an example that uses an inline function to return the maximum of two numbers:

#include<iostream> 
 
usingnamespace std; 

inlineintMax(int x,int y){return(x > y)? x : y;}   

    


// program's main function int main ( ) {
 


   cout <<"Max (20,10): "<<Max(20,10)<< endl;
   cout <<"Max (0,200): "<<Max(0,200)<< endl;
   cout <<"Max (100,1010): "<<Max(100,1010)<< endl;return0;}            
    

When the above code is compiled and executed, it produces the following results:

Max(20,10):20Max(0,200):200  
  

    1. Loop statements and switch statements are not allowed in inline functions;   
    2. The definition of the inline function must appear before the first call of the inline function;   
    3. The function defined inside the class description in the class structure is an inline function.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325684049&siteId=291194637