C language, pre-processor features:
1. # Replace the header file of include <> or ""
2.# Define <identifier> <replacement token list> Object replacement (Object-like)
Object replacement is separated by the first space, followed by the replacement token list
3. # define <identifier> (<parameter list>) <replacement token list> function replacement (Function-like)
There cannot be any blank characters between <identifier> (<parameter list>) function replacements. However, there can be spaces between calls.
When replacing a function, pay attention to the priority and type of the parameter table. If -- ';' is required in the replacement block, it is encapsulated with do {} while (0,
Note that there cannot be ';' At the end of the macro definition. Otherwise, if-else statements are prone to errors.
4 # Conditional compilation options such as ifdefine
In the macro definition, it is easy to make a mistake in the use of ##and.
# Connect two parameters,
# Define Mycase (item, ID )\
Case ID :\
Item ##### ID = ID ;\
Break
Switch (X ){
Mycase (widget, 23 );
}
Mycase (widget, 23 ); Is extended
Case 23 :
Widget_23 = 23 ;
Break ;
# Converting a parameter into a string
# Define Quoteme (x) # x
Printf ( " % S \ n " , Quoteme ( 1 + 2 ));
After replacement ==>
Printf ( " % S \ n " , " 1 + 2 " );
When using ## and #, if you want to replace macro-defined parameters with macros (use their values)
Instead of using the parameter name, useIndirect access.
The following are two examples:
Bytes -----------------------------------------------------------------------------------------------------------
Enum {
Oldersmall = 0 ,
Newerlarge = 1
};
# Define Older newer
# Define Small large
# Define _ Replace_1 (older, small) Older # small
# Define _ Replace_2 (older, small) _ replace_1 (older, small)
Void Printout ( Void )
{
// _ Replace_1 (older, small) becomes oldersmall (not newerlarge ),
// Despite the # define callabve.
Printf ( " Check 1: % d \ n " , _ Replace_1 (older, small ));
// The parameters to _ replace_2 are substituted before the call
// To _ replace_1, so we get newerlarge.
Printf ( " Check 2: % d \ n " , _ Replace_2 (older, small ));
}
Results Is :
Check 1 : 0
Check 2 : 1
-----------------------------------------------------------------------------
# Define Foo bar
# Define Quoteme _ (x) # x
# Define Quoteme (x) quoteme _ (x)
The Code
Printf ( " Foo = % s \ n " , Quoteme (FOO ));
After expansion ==>
Printf ( " Foo = % s \ n " , " Bar " );