A summary of define usage of C + +

Source: Internet
Author: User

1, define--(no parameter macro definition)

Usage: The general form is: #define Identifier string

(1) "#" means that it is a pre-processing command, usually "#" is the pre-processing command;

"Define" defines the command for the macro; "identifier" is the defined macro name; "string" can be a constant, an expression, a string, and so on.

(2) In addition to the frequently used such as "#define MAXNUM 100", there are many other flexible usages, such as "#define M", note that the macro definition of the expression () is necessary, otherwise in the operation such as "2*m+2" error occurs.

(3) Define the end of the macro definition does not require a semicolon (if you add a semicolon, it will be substituted with a semicolon), define just do a simple text substitution.

(4) The scope is the beginning of the macro definition, to the end of the source program, the terminating definition field is available "#undef M".

(5) If the macro name is called in the form of a string, no substitution is made, such as printf ("I M O").

(6) can be nested for definition, such as

#define PI 3.14

#define S Pi*r*r

(7) It is customary to write the macro name in uppercase to distinguish between common variables.

2. The difference between define and typedef

Define macro definition is done at preprocessing time, the typedef is really compile-time processing, typedef is not a simple substitution, but the type specifier is renamed.

For example:

#define P1  int*     P1 A, b;               Equivalent to int* A, B, at which point A is an int pointer and b is an int integer. typedef int* P2;        P2 A, B;            Indicates that both A and B are int pointers.            

3. Define (with parameter macro definition) usage

The general form is: #define Macro name (formal parameter) string

What is the longest #define MAX (A, B) (a>b)? A:b

(1) There must be no spaces between the macro name and the formal parameter. If the write as #define MAX (A, B) (a>b)? A:B, Max represents the entire back part.

(2) parameters defined with the parameter macro are not allocated memory.

(3) A formal parameter in a macro definition is an identifier, and an argument in a macro invocation can be an expression.

#define SQ (y) (y) * (y)      int main () {  int A, SQ; printf ("Enter a value:"), scanf ("%d", &a); sq = sq (a + 1); printf ("sq= %d\n ", sq); return 0; }/  * The first behavior macro definition in the previous example, the formal parameter is Y. The argument in the seventh line of the macro call is a + 1 is an expression, in the macro expansion, with a + 1 substitution y, and then (y) * (y) substitution sq, the following statement: sq = (A + 1) * (a + 1);      The call is different, and the value of the argument expression is then given to the formal parameter when the function is called. In the macro substitution, the actual parameter expression is not calculated directly as the substitution. */

(4) In a macro definition, formal parameters within a string are usually enclosed in parentheses to avoid errors. In the macro definition in the example above (y) * (y) the expression y is enclosed in parentheses, so the result is correct. If the brackets are removed, the program is changed to the following form:

#defineSQ (y) y*yintMain () {intA, sq; printf ("Please enter a value:"); scanf ("%d", &a); sq= SQ (A +1); printf ("sq=%d\n", sq);return 0; } /*in the above example, the first behavior of the macro definition, the formal parameter is Y. The argument in the seventh line of the macro call is a + 1 is an expression, in the macro expansion, with a + 1 substitution y, and then (y) * (y) substitution sq, the following statement: sq = (A + 1) * (a + 1); is different, the value of the argument expression is obtained by the function call and the formal parameter is given. In the macro substitution, the actual parameter expression is not calculated directly as the substitution.
Input a number:3 sq=7*/

(5) Multi-line definition of define. Define can replace multiple lines of code, such as the macro definition in MFC

#define MACRO (Arg1, arg2) do{/     stmt1;     /     stmt2;    /    while (0)/    * The key is to add a "/"  to each line break*/ 

4. Differences between define macros and functions

(1) Macro definitions can help us prevent errors, improve code portability and readability, and more. To see an example, compare two numbers or the size of an expression, first we write it as a macro definition:

First use the macro definition: #define MAX (A, B) ((a) > (b)? ( A): (b))

Followed by a function: int max (int a, int b) {return (a > B a:b)}

Obviously, we don't choose to use a function to accomplish this task for two reasons:

First, the function call brings extra overhead, it needs to open up a stack of space, record the return address, press the parameter stack, return from the function and release the stack. This overhead will not only reduce the efficiency of the code, but also greatly increase the amount of code, and the use of macro definitions in terms of code size and speed is better than the function;

Second, the parameters of the function must be declared as a particular type, so it can only be used on a specific type of expression, and if we want to compare the size of two floating-point types, we have to write a comparison function specifically for floating-point types.   Conversely, the macro definition above can be used for shaping, long shaping, single float, double floating-point type, and any other type that can be used to compare value sizes with the ">" operator, that is, macros are type-independent .

The disadvantage of using a macro, compared to using a function, is that each time a macro is used, a copy of the macro definition code is inserted into the program. Unless the macro is very short, using a macro greatly increases the length of the program. There are some tasks that cannot be implemented with functions at all, but are well-defined with macros. For example, parameter types cannot be passed as arguments to a function, but they can be passed to a macro with parameters. Look at the following example:

#define MALLOC (n, type) ((type *) malloc ((n) * sizeof (type)))

With this macro, we can assign a space to any type we specify and return a pointer to that space. We can look at the exact working process of this macro:

int *ptr;    5 int );     // expand this macro to the following result:   PTR = (int *) malloc ((5sizeof(int));     

This example is one of the classic applications of macro definition, the function can not be completed, but the macro definition can not be abused, usually, if the same code needs to appear in several parts of the program, a better way is to implement it as a function.

(2) The following summary and the difference between the macro and function, for everyone to write code, this is a summary from the "C and Pointer" book.

Code Length #define宏: The macro code is inserted into the program each time it is used . In addition to very small macros, the length of the program will grow substantially; the function code appears only in one place, and each time the function is used, the same code in that place is called .

"Speed speed" #define宏: Faster function: There is a function call, the extra overhead of returning

"Character Precedence" #define宏: The evaluation of macro parameters is in the context of all surrounding expressions, unless they are enclosed in parentheses, the precedence of the neighboring operator may produce unpredictable results. Function: The function parameter is evaluated only once at the function call, and its result value is passed to the function. The evaluation result of an expression is more predictable.

Evaluate #define宏: When parameters are used for macro definitions, they are evaluated every time, and because of multiple evaluation, parameters with side effects can produce unpredictable results. Functions: Arguments are only used once before a function call, and multiple arguments in a function do not result in multiple evaluation procedures, and the side effects of the parameters do not cause any special problems.

Parameter type #define宏: The macro is not type-independent, as long as the operation of the parameter is legal, it can be used for any parameter type. functions: The parameters of the function are related to the type, and if the arguments are of different types, different functions need to be used, even if the tasks they perform are the same.

A summary of define usage of C + +

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.