PostHeaderIcon Use const Instead of #define When Possible

The topic  this week is about safety programming~

Let’s begin with a piece of code:

// Code has lots of problems (don’t code like this)

#define WIDTH 8 – 1 // Width of page – margin
void print_info() {
// Width in points
int points = WIDTH * 72;
std::cout << “Width in points is “ <<points << std::endl;

What’s WIDTH? If you answered 7 you got it wrong.

The pre-processor is a very literal program.

The value of WIDTH is literally 8 – 1.

But everyone knows that 8 – 1 is 7 right? Not everyone. C++ does not. Especially when used in a expression. The line:

int points = WIDTH * 72;

is translated by the pre-processor into:

int points = 8 - 1 * 72;

As a result, the value of points is not what the programmer intended.

#define is come from C,

Now use const instead of #define whenever possible.

If we had defined width as:

static const int WIDTH = 8 – 1; // Width of page – margin

then our calculations would be correct.

That’s because we are now defining WIDTH using C++ syntax, not pre-processor syntax.

Using const has another benefit. If you make a mistake in the #define statement,

the problem may not show up until you actually use the constant.

The C++ compiler performs syntax checking on const statements.

Any syntax problems with these statements show up immediately

and you don’t have to guess where the problem occurred.

If you must use #define, please put parenthesis around the value:

#define WIDTH (8 – 1) // Good code

#define SQUARE(x) ((x) * (x)) // Recommend

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