Define inline Function in C++
What is the purpose of inline functions?
In a broad sense, the idea behind
inline functions is to insert the code of a called function at the point where the function is called. If done carefully, this can improve the application's performance in exchange for increased compile time and possibly (but not always) an increase in the size of the generated binary executables.
Read the fine print; it does make a difference. It is useful to distinguish between
- "inline", a keyword qualifier that is simply a request to the compiler, and
- "inlined" which refers to actual inline expansion of the function.
The expansion is more important than the request, because the costs and benefits are associated with the expansion.
Fortunately C++ programmers normally do not need to worry whether an inline function actually is inlined, since the C++ language guarantees that the semantics of a function cannot be changed by the compiler just because it is or is not inlined.
This is an important guarantee that changes the way compilers might optimize code otherwise.
C programmers may notice a similarity between
- inline functions and
- #define macros.
But do not push that analogy too far, as they are different in some important ways. For example, since inline functions are part of the language,
it is generally possible to step through them in a debugger, whereas macros are notoriously difficult to debug. Also, macro parameters that have side effects can cause surprises if the parameter appears more than once (or not at all) in the body of the macro, whereas inline functions don’t have these problems. Finally, macros are always expanded, but inline functions aren’t always inlined.
The C++ Programming Language
Explicit inline Functions
The inline
specification can be used explicitly with member functions defined at file scope.
This avoids having to clutter the class definition with function bodies.
struct ch_stack {
.....
void reset();
void push(char c);
.....
};
inline void ch_stack::reset()
{
top = EMPTY;
}
inline void ch_stack::push(char c)
{
assert(top != FULL);
top++;
s[top] = c;
}
Explicit Inlining
In explicit inlining, the prototype in the class definition is preceded by the keyword inline.
The member function defintion is defined outside the class definition, and is also preceded by the keyword inline.
Example:
class Date{
public:
inline Date(int,int,int);
inline void setdate(int,int,int);
void showdate(); // not inlined
// additional member functions
private:
int month;
int day;
int year;
};
inline Date::Date(int mm,int dd,int yy){
month = mm;
day = dd;
year = yy;
}
inline void Date::setdate(int mm,int dd,int yy){
month = mm;
day = dd;
year = yy;
}
void showdate(){
cout << month << '/' << day << '/' << year;
}