Summary of define usage in C/C ++

Source: Internet
Author: User

1. define -- (without macro Parameter definition) is generally used in the format of # define identifier string (1) "#", which indicates that it is a preprocessing command. All operations starting with "#" are preprocessing commands; "define" is a macro-defined command; "identifier" is the macro name defined; "string" can be a constant, expression, string, and so on. (2) In addition to the frequently used "# define MAXNUM 100", there are other flexible usage such as "# define M (y * y + 3 * y )", note that () is required in the expression. Otherwise, an error occurs during the "2 * M + 2" operation. (3) there is no need for a semicolon at the end (if a plus sign is added, it will be replaced with a semicolon ). (4) define only performs simple text replacement. (5) The scope starts with macro definition and ends with the source program. The "# undef M" can be used to terminate the definition domain ". (6) If the macro name is called as a string, it will not be replaced, such as printf ("I M O "). (7) can be nested for definition. For example, # define PI 3.14 # define s pi * R (8) is used to write macro names in uppercase to distinguish common variables. 2. Differences between define and typedef the define macro definition is completed in Preprocessing. typedef is actually processed during compilation. typedef is not a simple replacement, but a Rename of the type specifier. For example: # define P1 int * typedef int * P2; P1 a, B; // equivalent to int * a, B. At this time, a is an int pointer, and B is an int integer. P2 a, B; // indicates that both a and B are int pointers. 3. define (with macro Parameter definition) is generally used in the form of: # The longest define macro name (shape parameter) string # define MAX (a, B) (a> B )? A: B (1) there cannot be spaces between macro names and parameters. If the preceding formula is # define MAX (a, B) (a> B )? A: B, then MAX indicates the whole part. (2) parameters with macro definitions do not allocate memory. (3) The form parameter in the macro definition is the identifier, and the real parameter in the macro call can be an expression. # Define SQ (y) * (y) main () {int a, sq; printf ("input a number:"); scanf ("% d ", & a); sq = SQ (a + 1); printf ("sq = % d \ n", sq);} The first behavior macro in the preceding example is defined as y. In macro calls of the seventh row of the program, the real parameter is a + 1, which is an expression. During macro expansion, a + 1 is used to replace y, and (y) * (y) is used to replace SQ, obtain the following statement: sq = (a + 1) * (a + 1); this is different from the function call, when calling a function, evaluate the value of the real parameter expression and then assign it to the form parameter. In macro substitution, the real parameter expressions are replaced directly without calculation. (4) In macro definition, the form parameters in the string are usually enclosed in parentheses to avoid errors. In the macro definition in the preceding example, y in the (y) * (y) expression is enclosed in parentheses, so the result is correct. If you remove the brackets, change the program to the following format: # define SQ (y) y * y main () {int a, sq; printf ("input a number :"); scanf ("% d", & a); sq = SQ (a + 1); printf ("sq = % d \ n", sq);} the running result is: input a number: 3 sq = 7 (5) define multi-line definition define can replace multi-line code, for example, MACRO definition in MFC # define MACRO (arg1, arg2) do {// * declarations * // stmt1;/stmt2 ;//*... * //} while (0)/* (no trailing;) */The key is to add a "/" 4. Difference Between the define macro and the function during each line feed (1) macro definition can help us prevent errors and improve code portability and readability. Let's look at an example to compare two numbers or expression sizes. First, we write them into macro definitions: # define MAX (a, B) (a)> (B) (): (B) Second, use the function to implement: int max (int a, int B) {return (a> B a: B)} Obviously, we will not choose to use functions to complete this task. There are two reasons: First, function calling brings additional overhead. It needs to open up a stack space, record the return address, and press the parameters on the stack, the stack is also released from the function returned. This overhead not only reduces the code efficiency, but also increases the amount of code, and the use of macro definition is superior to the function in terms of code size and speed. Secondly, the function parameter must be declared as a specific type, so it can only be used in an appropriate type expression. If we want to compare the size of two floating point types, you have to write another comparison function for the floating point type. On the contrary, the macro definition above can be used for integer, long integer, single floating point, Double Floating Point, and any other type that can use the ">" operator to compare the value size. That is to say, macros are irrelevant to types. Compared with using a function, the disadvantage of using a macro is that every time you use a macro, a copy of the macro-defined code will be inserted into the program. Unless the macro is very short, the use of the macro will greatly increase the length of the program. Some tasks cannot be implemented by functions at all, but can be well implemented by macro definition. For example, the parameter type cannot be passed to the function as a parameter, but the parameter type can be passed to the macro with the parameter. Take the following example: # define MALLOC (n, type)/(type *) malloc (n) * sizeof (type) use this macro, we can allocate a specified space for any type and return a pointer to the space. We can observe the exact Working Process of this macro: int * ptr; ptr = MALLOC (5, int); the result after the macro is expanded: ptr = (int *) malloc (5) * sizeof (int); this example is one of the typical macro-defined applications. It completes functions that cannot be completed by functions, but macro definition cannot be abused. Generally, if the same code needs to appear in several places of the program, a better way is to implement it as a function. (2) The following is a summary of the differences between macros and functions for you to use when writing code. This summary is taken from the book C and pointers. Code length # define macro: the macro code is inserted into the program every time it is used. Except for very small macros, the length of the program will increase significantly. function: Function Code only appears in one place: every time you use this function, all calls the same code execution speed in that place # define macro: Faster function: There is a function call, and the returned additional overhead operator priority # define macro: macro parameters are evaluated in the context of all the surrounding expressions. Unless they are enclosed in parentheses, the priority of the adjacent operators may produce unpredictable results. Function: Evaluate a function parameter only once when it is called. The result value is passed to the function. The evaluation result of an expression is easier to predict. Parameter evaluation # define macro: When a parameter is used for macro definition, it is re-evaluated every time. Because of multiple evaluations, parameters with side effects may produce unpredictable results. Function: the parameter is evaluated only once before the function is called. Using the parameter multiple times in the function does not result in multiple evaluate processes. The side effects of the parameter do not cause any special problems. Parameter type # define macro: the macro has nothing to do with the type. As long as the operation of the parameter is legal, it can be used for any parameter type. Function: function parameters are related to types. If the types of parameters are different, different functions are required, even if they execute the same task.

Related Article

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.