Chris Dedman-Rollet
~ Per Astra Ad Astra ~

Preprocessor Directive in C++


By
on

My strategy to be successful in my programming classes is to start learning before the actual class start. I am currently learning C++ in preparation for my C++ class this spring semester, and today I learned what was preprocessor directives. I will try to make a little summary for you here.

So, preprocessor directives are lines of code in C++ that preceded # symbol. It is simply a line of code that generates code.
This line will look like this:


#define IDENTIFIER value
                        
When you compile your code, the preprocessor will scan from top to bottom your code and will "clean up" before the compilation.
So, for example a simple code like this one:


#include <iostream>
#define NAME "Chris"

int main()
{
    std::cout << NAME << std::endl ;
    return 0;
}
                

NOTE: I am not using the command using namespace std; because I learned that it can confused the compiler if you name a variable with the same name "std".
Once the preprocessor cleaned up and rewritten the program it will become:


#include <iostream>

int main()
{
    std::cout << "Chris" << std::endl ;
    return 0;
}
                    

The good thing with directives is that the macro (a piece of code in a program, in our example it will be NAME) can be reused anywhere in your program.
I learned that you have predefined macros such as _LINE_ which will give you the line number where it is called in your program.

You have as well the macros without value, added with a conditional compilation (#ifdef, #endif), it can allow you to write what will or will not be compiled.
For example, this code:


#include <iostream>

// define the macro NAME
#define NAME 

int main()
{
#ifdef NAME
    // NAME is define
    std::cout << "Chris\n"; 
#endif

#ifdef JOB  
    // JOB is not define
    std::cout << "Student\n";
#endif

    return 0;
}
                    

The line with the macro NAME will be printed because NAME is defined at the beginning of the program, but the macro JOB will not be printed because JOB is not defined at the beginning of your program. You can do other more complex things with preprocessor directives but I will let you explore by yourself if needed (I am not 100% comfortable with more complex functions, yet).

Final words, I am now part of a discord server for programmers, and a member explained to me what I tried to explain to you in this article. You can join the server by clicking here!

I hope this was helpful to understand what was preprocessor directives. Happy coding! 😄