Inline Functions - Inline Functions Suppose that you wish...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
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 frequently-used 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 error-prone 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() { /* stuff */
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 02/27/2012 for the course CS 251 taught by Professor Staff during the Fall '08 term at Purdue University-West Lafayette.

Page1 / 4

Inline Functions - Inline Functions Suppose that you wish...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online