C++ #define Usage Guide

In C++, #define is used to define macros, which allow you to define an identifier as a specific value or expression. Defined macros can be used as constants in the program, simplifying the code and enhancing its maintainability.

Here is a simple example:

#define PI 3.14159
#define MAX(a, b) ((a) > (b) ? (a) : (b))

int main() {
    double radius = 5.0;
    double area = PI * radius * radius;
    
    int x = 10;
    int y = 20;
    int max_value = MAX(x, y);
    
    return 0;
}

In the example above, constants PI and a macro function MAX are defined, and then these macros are used in the function to calculate the area of a circle and obtain the maximum value of two numbers. During compilation, the preprocessor will expand the macros into their respective values or expressions, replace the macros in the corresponding code, and ultimately generate executable code.

bannerAds