C++ Tutorial/Function/inline function

Материал из C\C++ эксперт
Перейти к: навигация, поиск

A Demonstration of an Inline Function

<source lang="cpp">#include <iostream> inline int Double(int); int main() {

  int target;
  using std::cout;
  using std::cin;
  using std::endl;
  cout << "Enter a number to work with: ";
  cin >> target;
  cout << "\n";
  target = Double(target);
  cout << "Target: " << target << endl;
  target = Double(target);
  cout << "Target: " << target << endl;
  target = Double(target);
  cout << "Target: " << target << endl;
  return 0;

} int Double(int target) {

  return 2*target;

}</source>

function inlining

<source lang="cpp">#include <iostream> int radiation(int health); using namespace std; int main() {

   int health = 80;
   cout << "Your health is " << health << "\n\n";
   health = radiation(health);
   cout << "After radiation exposure your health is " << health << "\n\n";
   health = radiation(health);
   cout << "After radiation exposure your health is " << health << "\n\n";
   health = radiation(health);
   cout << "After radiation exposure your health is " << health << "\n\n";
   return 0;

} inline int radiation(int health) {

   return (health / 2);

}</source>

Inline Functions

<source lang="cpp">#include <iostream> using namespace std;

inline int max(int a, int b) {

 return a>b ? a : b;

}

int main() {

 cout << max(10, 20);
 cout << " " << max(99, 88);
  
 return 0;

} // As far as the compiler is concerned, the preceding program is equivalent to this one: /*

  1. include <iostream>

using namespace std;

int main() {

 cout << (10>20 ? 10 : 20);
 cout << " " << (99>88 ? 99 : 88);
  
 return 0;

}

  • /</source>

Inline functions work best on short functions that are used repeatedly. This example calculates the square of an integer.

<source lang="cpp">#include <iostream> using namespace std; inline long squareit(int iValue) {return iValue * iValue;}

int main() {

int iValue = 5;
cout << squareit(iValue) << endl;
return (0);

}</source>