Another common use of the C #define macro expansion facility is to avoid function call overhead for small functions. Some functions are so small that the overhead of invoking the function call takes more time than the body of the function itself. C++ provides the inline keyword to inform the compiler to place the function inline rather than generate the code for calling the routine. For example, the macro
#define max (x, y) ((x)>(y)?(x):(y))
can be replaced for integers vy the C++ inline function
inline int max (int x, int y)
{
return (x > y ? x : y);
}
When a similar function is needed for multiple types, the C++ template mechanism can be used.
Macro expansion can lead to notorious results when encountering an expression with side effects, such as
max (f(x), z++);
which, after macro expansion becomes:
((f(x)) > (z++) ? (f(x) : (z++));
The variable z will be incremented once or twice, depending on the values of the x and y arguments to the function max(). Such errors are avoided when using the inline mechanism.
When defining a C++ class, the body of a class member function can also be specified. This code is also treated as inline code provided it does not contain any loops (e.g., while). For example:
class A {
int a;
public:
A() { }
// inline
int Value()
{
return a;
}
// inline
}
Since the code for both the constructor A() and the member function Value() are specified as part of the class definition, the code between the braces will be expanded inline whenever these functions are invoked.
No comments:
Post a Comment