PostHeaderIcon Use inline Functions Instead of Parameterized Macros

Let’s begin with an example.

Consider the following case:

#define SQUARE(x) ((x) * (x))
int i = 7;
int j = SQUARE(i++);

What’s the value of j?

The answer is that it’s compiler dependent.

 And the value of i is definitely not 8. Why? Just look at the code after the macro is expanded:

int j = ((i++) * (i++));

From this we can see that i is increment twice.

Also since the order of the operations is not specified by the C++ standard,

the actual value of j is compiler dependent.

Now use inline functions instead of #define whenever possible.

Let’s see code with an inline function:

static inline int square(int x) {
return (x * x);
}

Now when this function is called two things happen:

First, j gets the correct value ,

Second,i is incremented once.

In other words, the code behaves just like it is written.

And having something look and act the same way is a beautiful way for programming.

Note: Someone I’m sure will point out that the macro works for any type and is effective,

But the inline function only works for one type,like integers.No, you are wrong, if we do this

with a  inline version function template,what you concern will be solved,right?

I’ll introduce it later~

13,966 views

Leave a Reply

Your email address will not be published. Required fields are marked *

*


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


Copyright © 2010 - C++ Technology. All Rights Reserved.

Powered by Jerry | Free Space Provided by connove.com