![]() |
VOOZH | about |
Macros are shortcuts or placeholders that the preprocessor replaces before the code is compiled. They are defined using #define and can be used to create constants or code snippets.
Square of 7 is 49
Macros can be classified into four types in C++:
These are used to define constant values — like replacing a word with a fixed number or text.
Example:
In this example, PI is defined as an object-like macro, and whenever PI appears in the code, it is replaced with the value 3.14159.
Area of circle with radius 4 is 50.2654
These macros look like functions, but they are just text replacements.
Example:
In this example, PRINT(x) is a function-like macro that takes an argument x and expands to a function that prints the value of x.
Value is: 42
These are used to control which parts of the code should be compiled, based on whether something is defined or not.
Example:
[DEBUG] x = 5 [DEBUG] y = 10 [DEBUG] sum = 15 Sum: 15
Predefined macros are special macros that are already built into the C++ compiler.
You don't need to define them — they are automatically available in your program.
The following are some commonly used predefined macros in C++:
In this example, __LINE__ is replaced with the current line number, __FILE__ with the source file name and __DATE__ with the compilation date. These can be handy for debugging and logging.
This is line 10 in file ./Solution.cpp Compiled on Nov 7 2023