Define usage and precautions

Source: Internet
Author: User
Tags define function

# Define is a macro definition Command provided in C language. Its main purpose is to provide programmers with some convenience in programming and improve the program running efficiency to a certain extent, however, when learning this command, you often cannot understand the essence of the command, and there is always some confusion here. The command is misused during programming, so that the running of the program is inconsistent with the expected purpose, or when reading programs written by others, it is difficult to understand the running results. The basic usage and special features are described in detail below.

I. # basic define usage
1 # define command profiling
1.1 # define concept
# The define command is a macro definition command in C language. It is used to define an identifier as a string. This identifier is called a macro name and the defined string is called a replacement text. The command has two formats: A simple macro definition and a macro definition with parameters.
(1) simple macro definition:
# Define <macro name> <string>
Example: # define PI 3.1415926
(2) macro definition with Parameters
# Define <macro name> (<parameter table>) <macro>
Example: # define A (x) x
After an identifier is defined by a macro, It is a macro name. In this case, the macro name appears in the program. Before the program is compiled, replace the macro name with the defined string, which is called macro replacement, macro replacement is a simple replacement.
1.2 timing of macro replacement
To truly understand the role of # define, let's take a look at the processing process of the C language source program. When we compile the compiled source program in an integrated development environment such as Turbo C, the process of preprocessing, compilation, compilation, and connection is actually completed:
(Preprocessing) (Compilation) (assembly) (Link)
Source program ----------> modified source program -------------> assembler ---------> relocated target program -----------> executable Target Program
The pre-processor generates the compiler input, which implements the following functions:
(1) File Inclusion
You can extend # include in the source program to the file body, that is, find and expand the contained. h file to the position where # include is located.
(2) Conditional compilation
Based on the # if and # ifdef compiling commands and their post-condition, the Preprocessor includes or excludes some part of the source program. Generally, the excluded statements are converted into empty rows.
(3) macro expansion
The Preprocessor expands the macro reference in the source program file into the corresponding macro definition, that is, the # define function described in this article, which is completed by the Preprocessor. The source program processed by the pre-processor is different from the previous source program. In this stage, the work is purely replaced and expanded, and there is no computing function, so long as you can really understand the # define command, this command will not cause misunderstanding and misuse.
2 # define FAQs
2.1 problems with simple macro definition
In the use of a simple macro definition, it is easy to misunderstand and misuse when the string represented by the text is replaced by an expression. For example:
Example 1 # define N 2 + 2
Void main ()
{
Int a = N * N;
Printf ("% d", );
}
(1) A problem occurs: There is a macro definition command in this program. Macro N represents a string of 2 + 2, and there is a use of macro N in the program. when reading this program, the easy problem is that we first solve N as 2 + 2 = 4, and then use multiplication when calculating a in the program, that is, N * N = 4*4 = 16, in fact, the result of this question is 8. Why is there such a big deviation?
(2) Problem Analysis: As described in section 1, macro expansion is completed in the pre-processing phase. In this phase, the replacement text is only considered as a string, and no computation occurs, during expansion, where macro N appears, it simply uses string 2 + 2 to replace N without adding any symbols, therefore, after the program is expanded, the result is a = 2 + 2*2 + 2, after calculation = 8, which is the essence of macro replacement, how can I write a program to complete the calculation of result 16?
(3) solution: Write the macro definition in the following format:
# Define N (2 + 2)
This can be replaced with (2 + 2) * (2 + 2) = 16
2.2 problems with macro definition with Parameters
It is easy to misunderstand the use of macro definitions with parameters. For example, we need a macro to replace the square of any number, which requires parameters to replace the macro-defined parameters with actual parameters in the program. Generally, students are easy to write as follows:
# Define area (x) x * x
This is very prone to problems in use, see the following program
Void main ()
{
Int y = area (2 + 2 );
Printf ("% d", y );
} The parameter is 2 + 2. The result should be 4*4 = 16, but it is incorrect because the actual result of this program is 8, it still fails to follow purely simple replacement rules, and is replaced by calculation first. In this program, 2 + 2 is the parameter in the area macro, replace x in the macro definition with 2 + 2*2 + 2 = 8. If we follow the solution in (1), can we enclose 2 + 2, that is, enclose x in the macro? # Define area (x) * (x). For area (2 + 2), replace it with (2 + 2) * (2 + 2) = 16, but what about area (2 + 2)/area (2 + 2? Again wrong, I forgot to follow the rule of first replacement and then calculation. After this question is replaced, it will become (2 + 2) * (2 + 2)/(2 + 2) * (2 + 2) 4*4/4*4 according to the multiplication and division calculation rule, the result is 16/4*4 = 4*4 = 16. What should I do? The solution is to add a bracket to the entire macro, that is, # define area (x) * (x). Do not think this is unnecessary, without it, no.
To truly use the macro definition, remember to replace all the macro usage in the program with the string it represents. Do not add any other symbols on your own, if the calculation is complete, the running result is not written incorrectly. When macro replacement is used for programming, when there are more than one symbol in the string, brackets indicate the priority. If it is a macro definition with parameters, each parameter in the macro must be added with parentheses, add a bracket to the entire macro.

3. Advantages of macro definition
(1) convenient program modification
Use a simple macro definition to replace a constant that is frequently used in the program. In this way, when changing the constant, you do not need to modify the entire program, but only modify the macro-defined string, and when the constant is relatively long, we can use a short meaningful identifier to write the program, which is more convenient.
(2) Improve program running efficiency
Using macro definitions with parameters can call functions, reduce system overhead, and improve operation efficiency. As mentioned in C language, the use of functions can make the program more modular, easy to organize, and reusable. However, in the case of function calls, the field of function calls must be retained, so that after the sub-function is executed, it can return and continue execution. It also takes some time to restore the called function after the sub-function is executed, if the sub-function executes a large number of operations, the overhead of the conversion time can be ignored. However, if the sub-function does not have many functions, or even only one operation, such as a multiplication statement, this part of the conversion overhead is relatively large, but the macro definition with parameters will not have this problem, because it is expanded in the pre-processing stage, no conversion is required during execution, that is, it is executed locally. Macro definition can complete simple operations, but complex operations must be completed by function calls, and the macro definition occupies a large space for the target code. Therefore, you must determine whether to use macro definitions based on specific conditions.

4. The differences and comparisons between macros and const, inline, and emun are not discussed here.

Ii. Three special symbols in define :#,##,#@
# Define Conn (x, y) x # y
# Define ToChar (x) # @ x
# Define ToString (x) # x

X ## what does y mean? X connects to y, for example:
Int n = Conn (123,456); the result is n = 123456;
Char * str = Conn ("asdf", "adf") returns str = "asdfadf ";

Let's take a look at # @ x. In fact, a single quotation mark is added to x, and the returned result is a const char. For example:
Char a = ToChar (1); the result is a = 1;
Make an out-of-bounds test char a = ToChar (123); the result is wrong;
However, if your parameter contains more than four characters, the compiler reports an error! Error C2015: too character characters in constant: P

Finally, let's take a look at # x. You may also understand that it adds double quotation marks to x.
Char * str = ToString (123132); then str = "123132 ";

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.