C++

C++ Preprocessor: The Code in the Middle

In this article, we examine instructions given to the preprocessor and see how they are used in general. The preprocessor handles your code before the compiler interprets it. If you have been wondering just what the preprocessor is used for, this article explains.

The preprocessor literally changes your code (following the instructions you provide of course) and the result is a new source file, a temporary file that you cannot see but which is fed to the compiler. To specify which string tokens you want to have substituted you use the ‘#define’ directive.

For example, when you want to make use of arrays, you will have to specify how big you want one to be. By defining a MAX_STR_LEN token, you can define how big this array is once, instead of having to repeat this value throughout your code.

It is usually not a good idea to use ‘#define’ as a substitute for constants; the preprocessor merely does a string substitution and doesn’t perform any typechecking. Depending on your debugger it can make it difficult to interpret values during a debug session.

In this case it would have been better to use a constant value:

static int const MAX_STR_LEN=80;

There are programmers that use ‘#define’ to specify constants, so be wary when you detect these. Still I think it is better to use a ‘#define’ then it is to litter your values magically throughout the code.

Imagine that the maximum string length ise shrunk to 72,.and somewhere in the code there is a for-loop that was overlooked, and would still loop until 80. An overflow has been created and worse yet, this may only become clear when the application is run in optimized mode! The loop will modify a section of the memory, causing your application to crash in a mysterious way… oh the agony when you discover the overlooked for-loop.

Sometimes string substitution can be used to help makes things clearer as well… though some consider the following deviation to be distracting: