This preview shows pages 1–3. Sign up to view the full content.
This preview has intentionally blurred sections. Sign up to view the full version.View Full Document
Unformatted text preview: [ Viewing Hints ] [ Exercise Solutions ] [ Volume 2 ] [ Free Newsletter ] [ Seminars ] [ Seminars on CD ROM ] [ Consulting ] Thinking in C++, 2nd ed. Volume 1 2000 by Bruce Eckel [ Previous Chapter ] [ Table of Contents ] [ Index ] [ Next Chapter ] 9: Inline Functions One of the important features C++ inherits from C is efficiency. If the efficiency of C+ + were dramatically less than C, there would be a significant contingent of programmers who couldnt justify its use. In C, one of the ways to preserve efficiency is through the use of macros , which allow you to make what looks like a function call without the normal function call overhead. The macro is implemented with the preprocessor instead of the compiler proper, and the preprocessor replaces all macro calls directly with the macro code, so theres no cost involved from pushing arguments, making an assembly-language CALL, returning arguments, and performing an assembly-language RETURN. All the work is performed by the preprocessor, so you have the convenience and readability of a function call but it doesnt cost you anything. There are two problems with the use of preprocessor macros in C++. The first is also true with C: a macro looks like a function call, but doesnt always act like one. This can bury difficult-to-find bugs. The second problem is specific to C++: the preprocessor has no permission to access class member data. This means preprocessor macros cannot be used as class member functions. To retain the efficiency of the preprocessor macro, but to add the safety and class scoping of true functions, C++ has the inline function . In this chapter, well look at the problems of preprocessor macros in C++, how these problems are solved with inline functions, and guidelines and insights on the way inlines work. Preprocessor pitfalls The key to the problems of preprocessor macros is that you can be fooled into thinking that the behavior of the preprocessor is the same as the behavior of the compiler. Of course, it was intended that a macro look and act like a function call, so its quite easy to fall into this fiction. The difficulties begin when the subtle differences appear. As a simple example, consider the following: #define F (x) (x + 1) Now, if a call is made to F like this F(1) the preprocessor expands it, somewhat unexpectedly, to the following: (x) (x + 1)(1) The problem occurs because of the gap between F and its opening parenthesis in the macro definition. When this gap is removed, you can actually call the macro with the gap...
View Full Document
- Spring '11