Macros in C language are used to indirectly operate the compiling environment.
C language: Before compiling the source program normally, explain some special preprocessing commands to generate a new source program, then perform the normal compilation (to obtain the intermediate file and add the parameter/p ).
In the source program, in order to distinguish preprocessing commands from General C statements, all preprocessing command lines start with a symbol # And the macro must be capitalized, do not end with a semicolon.
The pre-processing command can appear in any position of the program, but it is used to writing at the beginning of the source program as much as possible. Its function ranges from its position to the end of the file.
Macro definition without parameters:
# Define statement sequence or expression
It is used to replace the sequence of idioms in the source program during compilation and preprocessing.
Macros are often used to define symbol constants and simplify the writing of some identifiers. Some of them make up for the deficiency of arrays with no variable number of elements in C language: Example:
# Include <stdio. h> # define IN scanf # define OUT printf # define N 2 void main () {int I = 0; char name [N] [20]; long num [N]; OUT ("Please input name and ID:"); for (I; I <N; I ++) {IN ("% s", name [I]); IN ("% ld", & num [I]) ;}for (I = 0; I <N; I ++) {OUT ("% s ", name [I]); OUT ("% ld", num [I]) ;}}
We will compile this code in VC6.0 without link. The compilation without link is set in VC6.0IDE as follows:
Add the/P parameter after Project Options. In this way, you choose to compile only
You can get the. I file after the pre-compilation. Let's open the. I file and see:
We can see that N is replaced with 2, IN is replaced with scanf, and OUT is replaced with printf! Therefore, such statements that control compiler preprocessing are usually called preprocessing commands!
A fun place for macros without parameters. Check the Code:
# Include "stdio. h" # define dodolook int g_a1 = 0x12345678; static int g_a2 = 0x87654321; dodolook void go (){//? X @? 1 ?? Go @ YAXXZ @ 4HA static int x = 0x88888888; printf ("% 08x", x);} int main (){//? X @? 1 ?? Main @ 9 @ 4HA static int x = 0x12312312; int a = 111; int B = 222; dodolook go (); return (0 );}