Thursday, December 03, 2009

A C++ trick: avoid #define

Hello, welcome to this space. I am a fan of C++; I use if for my scientific projects, with focus on high performance. So every now and then you will see a post about some trick for practical C++ programming.

Whenever you create a new program, the need for constants can arise; it is a common practice to use #define to solve the problem:
#define probability 0.75
You might be tempted to use #define because it only exists in preprocessing, so you are guaranteed memory is not allocated for the constant. Moreover, your definition can stand across source files by using #include. Your constant will also stand out of the rest of the code thanks to the syntax highlighting of your text editor.

However, using #define will prevent the compiler to help you check for the type safety and scope of the constant in your code. Here is an example inspired by Bjarne Stroustrup:

#define alpha 'a'
#define beta b[2]
class myCls {

int alpha;
int beta;
};

The g++ compiler will complain with
test.cc:8: error: expected unqualified-id before 'a'
So the bug about beta gets away and you might find yourself looking for the cause of some rare runtime bug months from now.
Your code must have room for improvement and evolution. It is not uncommon to have a simulation running OK but weeks later you want that precise constant to become a variable, so you want to repeat the program for a range of values. Given the preprocessor does not ensure type safety, it is likely that your program will not build when you finally switch from #define to const.
The computer is made to serve you, not the opposite. You should make all possible use of the power of your computer to help you check for type safety and overall consistency of the code you write. So take the opportunity of having the compiler give you a smoother programming experience by having const instead of #define. Use the compiler optimizations and learn about the cases in which const allocates space and cases in which it does not.

No comments:

Post a Comment

Is your comment or question:

1. Constructive?
2. Interesting?
3. Short?

If not, please post it in your own blog.