Inline Functions
Suppose that you wish to write a function in C to compute the maximum of two
numbers. One way would be to say:
int max(int a, int b)
{
return (a > b ? a : b);
}
But calling a frequentlyused function can be a bit slow, and so you instead use a
macro:
#define max(a, b) ((a) > (b) ? (a) : (b))
The extra parentheses are required to handle cases like:
max(a = b, c = d)
This approach can work pretty well. But it is errorprone due to the extra parentheses
and also because of side effects like:
max(a++, b++)
An alternative in C++ is to use inline functions:
inline int max(int a, int b)
{
return (a > b ? a : b);
}
Such a function is written just like a regular C or C++ function. But it IS a function
and not simply a macro; macros don't really obey the rules of C++ and therefore can
introduce problems. Note also that one could use C++ templates to write this function,
with the argument types generalized to any numerical type.
If an inline function is a member function of a C++ class, there are a couple of ways
to write it:
class A {
public:
void f() { /* stuff */ }
// "inline" not needed
};
or:
class A {
public:
inline void f();
};
inline void A::f()
{
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
This is the end of the preview.
Sign up
to
access the rest of the document.
 Fall '08
 Staff
 class a, len, Inline function, inline functions

Click to edit the document details