Why do we use inline and when do we use it?

PHOTO EMBED

Sat Apr 17 2021 00:49:25 GMT+0000 (Coordinated Universal Time)

Saved by @wowza12341 #c++

Part 1:

// Header.h
void func(); // Declares func()
 
// File1.cc
#include "Header.h"
void func() {   // Defines func()
   ...
}
 
// File2.cc
#include "Header.h"
...  // Do something else
func(); // Calls func()
  
  
  
  
  
  
Part 2:

// Header.h
inline void func() { // Defines func()
   ...
}
 
// File2.cc
#include "Header.h"
... // Do something else
... // Code for func()
content_copyCOPY

In part 1, here, the code that calls func() will be in a different part of the program executable from the code that contains the instructions for func(). The program will need to stop executing the code from File2, jump across to the code from File1 and start executing the instructions there. This involves the compiler adding some "bookkeeping" code to keep things in order; in particular, the program must know how to go back to File2's code. If there are function arguments or return values, these must be transferred around the program correctly. If we make func() an inline function, we have a situation like this (don't take this too literally!): Part 2 The inline keyword means we are asking the compiler to put the code for func() directly where it is called, instead of going through the usual function call procedure. This should be an optimization, because the program will not need the bookkeeping code. However, because there is an extra copy of the code everywhere it is called, this makes the executable larger, which may affect performance. Inline functions should be kept very short and simple. Also, the compiler is not obliged to actually inline the function - it's only a hint to it, which it can ignore. The other effect of "inline" is that the function is not subject to the "One Definition Rule". This rule says that a symbol can only be defined once in a program. Normally, if we write the definition of a function in a header, and include this header in several source files, we will get an error about multiple definitions of the function. If the function is made inline, then there is no problem. Incidentally, if you write the definition of a class member function inside the class, it is regarded as inline. This makes it possible to write out the full definition of a class and its member functions, in a header file, without having to use a .cpp file.

https://www.udemy.com/course/learn-advanced-c-programming/learn/lecture/3688332?%24web_only=true&~channel=email&~stage=published&utm_medium=email&utm_campaign=email&utm_source=sendgrid.com&_branch_match_id=890253272865013170#questions/14628310/