Example of Macro
Let’s explore a simple example of a macro in C++. Suppose we want to create a macro to calculate the square of a number. Here’s how we can define and use a macro:
C++
// C++ program to illustrate the macro definition #include <iostream> using namespace std; // Define a macro to calculate the square of a number #define SQUARE(x) (x * x) int main() { int n = 7; int result = SQUARE(n); // Expands to: (n * n) cout << "Square of " << n << " is " << result; return 0; } |
Square of 7 is 49
Explanation
In this example, the #define directive defines a macro named SQUARE(x) that takes an argument x and returns the square of that value. When we use SQUARE(n), it is expanded to (n * n) during preprocessing.
Macros In C++
C++ is a powerful and versatile programming language that offers many features to enhance code flexibility and maintainability. One such feature is macros, which are preprocessor directives used for code generation and substitution. Macros are an essential part of C++ programming and play a crucial role in simplifying code, making it more readable and efficient. In this article, we will learn about the macros in C++.
Contact Us