1. Preprocessing commands
In Article 1ArticleWe mentioned the pre-processor concept. A Preprocessor is used to process preprocessing commands. Preprocessing Commands include the following three types:
A. macro definition # define
B. File Inclusion # include
C. Conditional compilation # If # ifdef and so on.
2. Simple macro definition
We have used macro definitions extensively before and will not go into details here.
3. macro definition with Parameters
A macro with parameters is also called a FUNCTION macro.
A simple example:
# DefineMax (m, n) (m)> (n )? (M) :( n ))IntMain (Void) {Printf ("% D", Max (1, 2 ));Return0 ;}
I believe everyone understands this example. Here I will only describe one point:ProgramIn, there are a lot of (), that is to prevent the side effects of replacement, because the pre-processor does not understand the C language syntax rules, generally only for simple mechanical replacement, so if m, N is an expression, which is likely to cause problems.
For example:
# DefineMul (m, n) M * nIntMain (Void) {Printf ("% D", MUL (1 + 3, 3 + 1 ));Return0 ;}
This program is problematic. You can test it on your own.
So why do we need macros with parameters? There are two advantages:
A. higher efficiency. If it is defined as a general function, the program needs to store context information and press the parameter to stack during execution, but the macro definition obviously does not have such running overhead. (Here we can think about inline functions .)
B. There is no type restriction on macros. It is actually a parameter type overload. For example, in the max definition above, you can input an int type parameter or a double type parameter.
In my opinion, the most obvious disadvantage is that it may cause a program.Code.
4. trivial
# The operator can convert a macro-defined parameter to a string literal. For example:
# DefinePrint (Num) (printf (# num"= % D", Num ))IntMain (Void) {Print (10/2 );Return0 ;}
You can view the results by yourself.
# UNDEF command to cancel macro definition.