Macros in C++: How It Works & Why You Should Use It
For all C++ developers, we all know that there are many ways of using
#define directive is typically used to associate meaningful identifiers with constants, keywords, and commonly used statements or expressions. When the name of a macro is recognized in the program source text or the arguments of certain other preprocessor commands, it’s treated as a call to that macro. In practical terms, there are two types of macros. 1. Object-like macros take no arguments. 2. Function-like macros can be defined to accept arguments so that they look and act like function calls. Because macros don’t generate actual function calls, you can sometimes make programs run faster by replacing function calls with macros. So using macros, you can use concurrency with C++, which means you get a quicker compile time. But there is only one catch about macros: Once you’ve defined macros, you can’t redefine it to a different value without first removing the original definition. However, you can redefine the macros with exactly the same definition. Thus, the same definition may appear more than once in a program. The
#undef directive removes the definition of macros. Once you’ve removed the definition of the macro, you can redefine the macros to a different value.
Here is an example of
macros in action:
#define MY_MACROS parameters // parameters is optional
Thank you for reading and if you enjoyed this, please clap for this story! Thanks!