The usage and precautions of define

Source: Internet
Author: User

#define是C语言中提供的宏定义命令, the main purpose is to provide programmers with some convenience in programming, and to a certain extent, improve the efficiency of the program, but often in learning not to understand the nature of the command, always create some confusion here, in the programming of the misuse of the command, To make the program run inconsistent with the intended purpose, or to read the program written by others, the results of the operation to understand the error, which is bad for C language learning. The basic usage and special details are described below respectively.

First, #define的基本用法
1 #define命令剖析
1.1 #define的概念
#define命令是C语言中的一个宏定义命令, which is used to define an identifier as a string, which is called the macro name, and the defined string is called the replacement text. The command has two formats: one is a simple macro definition and the other is 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 body >
Example: #define A (x) x
When an identifier is defined by a macro, the identifier is a macro name. At this point, the macro name appears in the program, before the program is compiled, the macro name is replaced with the defined string, which is called the macro substitution, the substitution is not compiled, the macro substitution is a simple replacement.
1.2 Macro Replacement when the time comes
In order to really understand the role of # define, let's look at the process of C language source program. When we compile a well-written source program in an integrated development environment such as Turbo C, there are several processes that are actually preprocessed, compiled, assembled, and connected:
Pretreatment                      Compiler                                      Compilation Link
SOURCE program------------> Modified source program-------------> Assembler-----------> Relocatable target program-------------> executable Target Program
Where the preprocessor produces the input of the compiler, it implements the following functions:
(1) The file contains
You can extend the # include in the source program to the body of the file, i.e. locate and expand the contained. h file to the location of # include.
(2) Conditional compilation
The preprocessor includes a part of the source program in or out of the compilation commands, such as # if and #ifdef, and usually converts the excluded statement to a blank line.
(3) Macro expansion
The preprocessor expands the macro reference that appears in the source program file into the corresponding macro definition, which is what this article describes as the function of # define, which is done by the preprocessor. The source program processed by the preprocessor differs from the previous source program, where the work performed is purely a substitution and unwinding, without any computational function, so as long as you can really understand this when learning the # define command, it will not cause misunderstanding and misuse of this command.
2 #define使用中的常见问题解析
2.1 Simple macros define problems that occur in use
In the use of simple macro definitions, it is easy to misunderstand and misuse when the replacement text represents a string that is an expression. The following example:
Example 1 #define N
void Main ()
{
int a=n*n;
printf ("%d", a);
}
(1) The problem: there is a macro definition command in this program, macro n represents the string is the use of the macro N, in the program, the general students in the reading of the program, the problem is prone to solve the N is 2+2=4, and then in the program to calculate a when using multiplication, that is, n*n=4*4=16, In fact, the result of the problem is 8, why the result has such a large deviation?
(2) Problem resolution: As described in section 1, macro expansion is done in the preprocessing phase, this phase of the replacement text is just as a string, and there will be no calculation occurs, when the macro n appears in the expansion is simply the use of the string to replace N, does not add any symbols, So the result of the program is a=2+2*2+2, after the calculation = 8, which is the essence of macro substitution, how to write a program to complete the result of 16 of the operation?
(3) Workaround: The macro definition is written in the following form
#define N (+)
This will be replaced by (=16) * (* * *)
2.2 Problems with the macro definition with parameters
In the use of macro definitions with parameters, it is very easy to cause misunderstanding. For example, we need to make a macro substitution to find the square of any number, which requires the use of parameters to replace the parameters in the macro definition with actual parameters in the program. General students are easily written in the following form:
#define AREA (x) x*x
This is very easy to use in the problem, see the following program
void Main ()
{
int Y=area (+);
printf ("%d", y);
The argument given is that the parameter is the 4*4=16, the result should be a, but wrong, because the actual result of the program is 8, is still not able to follow the pure simple replacement of the rules, but also the first calculation and replace, in this program, is the area macro is the parameter, it should be replaced by the macro definition of x, That is replaced by 2+2*2+2=8.  What if we follow the solution in (1) and enclose it in the X-ray of the macro body? #define AREA (x) (x) * (x), for area (*./area), replaced by (+/-(+) * (+) * (*) = 16, can be resolved; Again wrong, or forget to follow the first substitution of the rules of the calculation, the problem will be replaced after the (* * +) * (* * +)/(4*4/4*4) * (* * * *) that is, according to the multiplication operation rules, the result is 16/4*4=4*4=16, that should be how? The workaround is to add a parenthesis to the entire macro body, that is, the # define area (x) (x) * (x)), do not feel that this is not necessary, without it, is not possible.
To be able to really use a good macro definition, it is important to remember that the use of the macro in the program to replace all of the characters it represents the string, do not take the liberty to add any other symbols, fully expanded after the corresponding calculation, will not write wrong running results. When programming with macro substitution, when there is more than one symbol in a string, the parentheses show precedence, and if it is a macro definition with parameters, enclose each parameter in the macro body with parentheses over the entire macro body.

3 Benefits of macro definition
(1) Modification of the convenience program
Using simple macros to define available macros instead of a constant used in the program, so that when the constant changes, not the whole program to modify, only the macro definition of the string can be, and when the constant is longer, we can use a shorter meaningful identifier to write the program, which is more convenient.
(2) Improve the operation efficiency of the program
Using a macro with parameters to define functions that can accomplish function calls can reduce system overhead and improve operational efficiency. As mentioned in the C language, the use of functions can make the program more modular, easy to organize, and reusable, but in the event of a function call, you need to retain the calling function of the field, so that the completion of the execution of the child function can return to continue execution, as well as the child function after the completion of the call function to restore the scene, If the child function performs more operations, this conversion time overhead can be ignored, but if the function of the child function is relatively small, or even a single point of operation, such as the operation of a multiplication statement, this part of the conversion cost is relatively large, but the use of parameters with the macro definition will not occur this problem, Because it is a macro expansion during the preprocessing phase, it does not need to be converted at execution time, which is executed locally. A macro definition can do simple things, but a complex operation is still done by a function call, and the macro definition occupies a relatively large target code space. So when you use it, you decide whether to use a macro definition, depending on the situation.

4. Differences and comparisons between macros and Const,inline,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# #y表示什么? Represents x connection Y, for example:
int n = Conn (123,456); The result is n=123456;
char* str = Conn ("asdf", "ADF") result is str = "ASDFADF";

To see #@x, in fact, is to add single quotation marks to x, the result is a const char. For example,
char a = ToChar (1); the result is a=1;
Do a cross-border test. Char a = ToChar (123); the result is wrong;
But if your parameter exceeds four characters, the compiler will give you an error! Error C2015:too many characters in Constant:p

Finally look at #x, and you know, he's giving X double quotes.
char* str = ToString (123132); str= "123132"

C. Declare a constant with pre-processing directive # # to indicate how many seconds are in 1 years? (Ignore leap year issues)

#define SECONDS_PER_YEAR (*24 *365) UL

1. Basic knowledge of #define grammar (use of parentheses, cannot end with semicolons, etc.)

2. Realize that this expression will overflow the integer number of a 16-bit machine-so use the long integer symbol l to tell the compiler that the constant is a long integer number.

3.UL: denotes long integer symbol

The usage and precautions of define

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.