C++ Preprocessor: The Code in the Middle - String Substitution
(Page 2 of 6 )
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.
#define MAX_STR_LEN 80
int main(int argc, char const *argv[]) {
int anArray[MAX_STR_LEN];
for ( int idx=0; idx<MAX_STR_LEN; ++idx )
anArray[idx]=0;
return 0;
}
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:
#define EVER ; ;
for ( EVER ) { …}
Next: String Manipulation >>
More C++ Articles
More By J. Nakamura