Inline Functions |
|
Overview |
When one function calls another, the calling function must send a request to the called function that would process it and return the necessary value, if any. C++ allows you to implement a function so that, when it is called, a copy of the whole function is placed where the function is being called. This means that the calling functions doesn't send a request to the function that performs the assignment: the function itself is accessed where it is needed. To create an inline function, type the inline keyword to its left when declaring the function. Here is an example: |
#include <iostream> using namespace std; inline double Sum(const double * Numbers, const int Count) { double s = 0; for(int i = 0; i < Count; i++) s += Numbers[i]; return s; } int main() { double Nbr[] = { 15.66, 18, 25, 128.62, 12.06, 22.18 }; double Total = Sum(Nbr, 6); cout << "Sum = " << Total << endl; return 0; }
If you first declare a function that would be defined somewhere else, when implementing the function, you can type or omit the inline keyword: |
#include <iostream> using namespace std; inline double Sum(const double * Numbers, const int Count); int main() { double Nbr[] = { 15.66, 18, 25, 128.62, 12.06, 22.18 }; double Total = Sum(Nbr, 6); cout << "Sum = " << Total << endl; return 0; } inline double Sum(const double * Numbers, const int Count) { double s = 0; for(int i = 0; i < Count; i++) s += Numbers[i]; return s; }
|
Copyright © 2003-2005 FunctionX, Inc. |
|