![]() |
VOOZH | about |
In C++, #define is a preprocessor directive used to define a macro. are a way to represent a fragment of code or a constant value by giving it a name. When the preprocessor encounters the macro name in the code, it replaces it with the corresponding code fragment or value that is defined using the #define preprocessor. In this article we will learn about using #define in C++.
We can define the two types of macro using #define:
#define MACRO_NAME valueThey are also called object-like macros by a number of people.
#define MACRO1_NAME value1
#define value1 final_value
#define MACRO_NAME (expression within brackets)We can also define a macro expression that takes parameters:
#define MACRO_NAME(parameters) (expression)These types of macros are also called function like macros.
The backslash (\) here works as the joiner of the two values.
#define MACRO_NAME value \
value2 \
value3 \
In the following example we have used #define to assign a constant value to PI so that PI can be referred later in the program to calculate the area of the circle.
Enter the radius of a circle: Area = 78.5625
In the following example we have used #define to define a for loop expression that will print the values present in an array.
Geeks for Geeks C++ Tutorial
ALL_USERS: 100
Welcome to GeeksforGeeks
The following are some important properties of macros:
Following are some applications of #define:
One of the major application of Macros in C was in the generic programming but it is not required in C++ as C++ have templates for generic programming.