C++ Tutorial/Function/inline function

Материал из C\C++ эксперт
Версия от 10:29, 25 мая 2010; Admin (обсуждение | вклад) (1 версия: Импорт контента...)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

A Demonstration of an Inline Function

#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;
}

function inlining

#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);
}

Inline Functions

#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:
/*
#include <iostream>
using namespace std;
   
int main()
{
   
  cout << (10>20 ? 10 : 20);
  cout << " " << (99>88 ? 99 : 88);
   
  return 0;
}
*/

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

#include <iostream>
using namespace std;
inline long squareit(int iValue) {return iValue * iValue;}
                               
int main()
{
 int iValue = 5;
 cout << squareit(iValue) << endl;
 return (0);
}