C++ define uses

usage of define in c++

define has many usages in C++ language, and it is sorted out here.

1. No parameter macro definition

A no-argument macro has no parameters following the macro name.
The general form of its definition is:

#define  标识符  字符串

The "#" in it indicates that this is a preprocessing command. Anything starting with "#" is a preprocessing command. "define" is a macro definition command. "Identifier" is the defined macro name. A "string" can be a constant, an expression, a format string, etc.
For example:

#define MAXNUM 99999

Thus MAXNUM is simply defined as 99999.

2. There are parametric macro definitions

The C++ language allows macros to take parameters. The parameters in the macro definition are called formal parameters, and the parameters in the macro call are called actual parameters.
For macros with parameters, in the call, not only the macro expansion is required, but also the actual parameters must be used to replace the formal parameters.
The general form of a macro definition with parameters is:

 #define  宏名(形参表)  字符串

Contains the individual parameters in a string . The general form of invoking a macro with parameters when in use is: macro name (actual parameter list);
for example:

#define add(x, y) (x + y)

int main()
{
    //输出“1 plus 1 is 2.5.”
    cout << "1 plus 1 is " << add(1, 1.5) << ".\n";

    system("pause");
    return(0);
}

This "function" defines addition, but this "function" has no type checking, which is a bit like a template, but it is not as safe as a template. It can be regarded as a simple template.

Note: The "function" is defined as (a + b). The reason for adding parentheses here is that the macro definition is only a simple replacement in the preprocessing stage. If the simple replacement is a + b, when you use 5 * When add(2, 3), it is replaced by 5 * 2 + 3, the value is 13, not 5 * (2 + 3), the value is 25.

Participate in more detailed usage methods: http://t.csdn.cn/yf99i

Guess you like

Origin blog.csdn.net/MWooooo/article/details/126599848