Wednesday, July 1, 2009

const Vs #define, what to use and when

const one of the features which was not present in C but was introduced in C++. Its interesting to know why would anyone use const to declare constant values and not #defines which are being used since ages and have done the work more or less without much trouble.

Well the problem with #define is that its a preprocessor directive. Which means it needs to be put in a .h file for sharing among different files. But if it just needs to be used in a single cpp file, it works like a charm. But imagine that you need to include it in several files. Then you are in a big mess. If you make a simple change in that .h file, the build process will compile all files that include the header file. Which in case of big projects can mean a lot of headache.

So welcome to const. This can help you get rid of this problem. Since these const variables are actually compiled and not used as in case of header files. There is no need to compile all files using const variables, provided you make use of forward declarations  in the cpp files.

Const does not mean that it does not have any downside. It does have a problem. If you have a large number of declarations they all take some memory and you now understand what it can lead to. But in most cases, const is actually better than #define. But you need to take that call.

Note: The above is based on my understanding. If you think otherwise, do let me know why.

1 comment:

Anonymous said...

Its a pretty late comment but the reason const was introduced in C++ is for type checking. #define have no type information and can lead to all kind of headaches.