Dark Horse programmer--C Language macros

Source: Internet
Author: User

Introduction to Macros 1. C language before compiling the source program, will be a number of special pre-processing instructions (such as the previous use of the # include file contains instructions), a new source program (this process is called the compilation preprocessing), and then the usual compilation

All preprocessor directives start with # and end without semicolons

2. Pre-processing instructions are divided into 3 types

1> macro Definition

2> conditional Compilation

The 3> file contains

3. Pre-processing instructions are executed before the code is translated into 0 and 1

4. The location of the preprocessing is casually written

5. Scope of preprocessing directives: starting from the line where the instruction was written, until the end of the file, you can use #undef to cancel the function of the macro definition

6. Macro names usually start with uppercase or K, and variable names are usually lowercase

Macro definitions can be divided into 2 types: macro definitions without parameters and macro definitions with parameters. One, macro definition without parameters 1. General form

#define Macro Name string

such as # define ABC 10

The string on the right can also be omitted, such as # define ABC

2. Role

It is used to define constants by replacing all "macro names" in the source program with the right "strings" when compiling preprocessing.

3. Use habits and attention

1> macro names are generally capitalized in order to distinguish them from variable names, but there is no syntax error in lowercase

2> the characters within the string that are enclosed in double quotation marks for the program, and does not replace the macro.

3> does not make a syntax check when it replaces a macro name with a string in the compilation preprocessing, but simply replaces the string. The source program that has expanded the macro name is checked for syntax only at compile time

The valid range of 4> macro names is from the defined position to the end of the file. If you need to terminate the scope of a macro definition, you can use the #undef command

5> you can refer to a macro name that you have defined when defining a macro

#define R  3.0#define PI 3.14#define L  2*pi*r#define S  pi*r*r

Example

1#include <stdio.h>2 #defineCOUNT 43 4 intMain ()5 {6     Char*name ="COUNT";7     8printf"%s\n", name);9     Ten     intAges[count] = {1,2, the, the}; One      A     #defineKcount 4 -      -      for(inti =0; i<count; i++) { theprintf"%d\n", Ages[i]); -     } -      -     //from this line, count this macro will expire + #undefCOUNT -      +     //int a = COUNT Write this error A      at     return 0; -}

second, macro definition with parameters1. General form

#define Macro Name (argument list) string

2. Role

When you compile preprocessing, replace all macro names in the source program with strings, and replace the arguments in the string with the parameters in the argument list on the right side of the macro name

3. Use note

There must be no spaces between the 1> macro name and the argument list, otherwise all strings following the space are substituted strings

2> macros with parameters are expanded, only simple characters and parameters are replaced, and no calculations are performed. So when you define a macro, you typically enclose the string's arguments in a single parenthesis.

3> calculation results are best also enclosed in parentheses.

4. Differences from functions

From the entire use of the process can be found that the macro definition with parameters, in the source program appears in the form and function very much like. But there is an essential difference between the two:

1> macro definition does not involve allocation of storage space, parameter type matching, parameter passing, return value problems

2> function calls execute while the program is running, and macro substitution occurs only during the compilation preprocessing phase. Therefore, the macro with parameters has higher execution efficiency than the function.

1#include <stdio.h>2 #definePingfang (a) ((a) * (a))3 4 intMain ()5 {6     intc = Pingfang (5+5)/pingfang (2);7     8printf"C is%d\n", c);9     Ten     return 0; One}

Concept of conditional compilation

In many cases, we want some of the code in the program to compile only if certain conditions are met, otherwise it does not participate in compilation (only the code that participates in the compilation will eventually be executed), which is conditional compilation .

First, basic usage
1 #if conditions ...  code1 ... 3 #elif conditions ...  code2 ... 5 #else6 ...  code3 7 #endif

1> If condition 1 is set up, then the compiler will put # if and #elif之间的code1代码编译进去(note: It is compiled, not executed, with the usual if-else is not the same)
2> If condition 1 is not established and condition 2 is set up, then the compiler will #elif and #else之间的code2代码编译进去

3> if conditions 1 and 2 are not true, then the compiler will #else and #endif之间的code3编译进去

4> Note that after the conditional compilation ends, add a #endif to the last face, or the consequences are serious.

5> #if and #elif后面的条件一般是判断宏定义而不是判断变量, because conditional compilation is a judgment done before compilation, and a macro definition is defined before compilation, and the variable is generated at run time, meaning it is used.

Two, give an example
1 #include <stdio.h> 2  3 #define MAX 4  5 int main () 6 {7 #if max = = 0 8     printf ("MAX is 0"); 9 #elif MA X > 010     printf ("Max is greater than 0"), one #else12     printf ("Max is less than 0"), #endif14     return 0;15}

In line 3rd, you define a macro max, which, of course, may be defined in the other header file in development, and is now written to the main function for illustrative purposes only. Note the conditional compilation statements for lines 7th through 13th.
Since Max is 11, the #elif condition is set, and the 10th line of code will be compiled, in fact, after the pre-processing of the compiler code is this:

The contents of the 1/*stdio.h file will replace the location of # include <stdio.h> */2 3 int main () 4 {5     printf ("Max is greater than 0"), 6     return 0;7}

The code becomes very concise and the output is:

Iii. other usage 1. Use of #if defined () and # if!defined ()

#if and #elif后面的条件不仅仅可以用来判断宏的值, you can also determine whether a macro has been defined. Like what:

1 #if defined (MAX) 2     ... code ... 3 #endif

If you have already defined Max as a macro, compile code into it. It does not control the value of Max, as long as Max is defined, the condition is set.

Conditions can also be reversed:

1 #if!defined (MAX) 2     ... code ... 3 #endif

If Max is not defined previously, the code is compiled in.

2. Use of #ifdef和 #ifndef

* The usage of #ifdef的使用和 # if defined () is basically consistent

1 #ifdef MAX2 ...     code ... 3 #endif

If you have already defined Max as a macro, compile code into it.

* The usage of #ifndef又和 # if!defined () is basically consistent

1 #ifndef MAX2 ...     code ... 3 #endif

If Max is not defined previously, the code is compiled in.

1#include <stdio.h>2 3 //as long as you write # If, you must add #endif on the last side4 5 intMain ()6 {7 #ifndef A8     //#ifdef A9     //#if!defined (A)Tenprintf"haha \ n"); One #endif A      -         return 0; -}

file contains

First, the basic concept

Actually, we already have contact. The file contains this directive, which is # include, which can copy the entire contents of a file into another file

Ii. general form 1.1th form # include < file name >

Find files directly in the directory where the C-language library function header files are located

2.2nd form #include "file name"

The system will look in the current directory of the source program, if not found, and then to the operating system path path to find, and finally to the C library function header file in the same directory to find

Third, the use of attention

1. #include指令允许嵌套包含, for example, A.H contains b.h,b.h containing c.h, but does not allow recursive inclusion, such as A.H contains B.h,b.h.

The following procedure is wrong

2. Using the # include directive may result in a single header file being included multiple times, reducing compilation efficiency

For example, the following conditions:

A one function is declared in One.h, and One.h is included in the Two.h, by the way, a single function is declared. (This does not write the implementation of the function, that is, the definition of the function)

If I want to use one and two two functions in main.c, and sometimes we don't necessarily know that two.h contains one.h, we might do this:

The code for MAIN.C after the pre-processing of the compilation is this:

1 void One (), 2 void One (), 3 void (), 4 int main () 5 {6 7     return 0;8}

Line 1th is caused by the # include "One.h", and the 2nd, 3 lines are caused by the # include "Two.h" (because Two.h contains one.h). As you can see, the one function is declared 2 times and is not necessary at all, which reduces compilation efficiency.

In order to solve this problem of repeating the same header file, we usually write the contents of the header file:

To explain the meaning, take one.h for example: When we first include "one.h", because there is no definition of _one_h_, so the condition of the 9th line is established, and then the 10th line defines the _ONE_H_ this macro, and then declare the one function in line 13, Finally, the conditional compilation ends in line 15. When the second # include "One.h", because previously defined _ONE_H_ this macro, so the 9th line of the condition is not set, jump directly to the 15th line of #endif, end conditional compilation. This is the simple 3-sentence code that prevents one.h content from being repeatedly included.

In this case, the MAIN.C:

#include "one.h" #include "two.h"

It becomes:

1//#include "one.h" 2 #ifndef _one_h_ 3 #define _ONE_H_ 4  5 void One (), 6  7 #endif 8  9//#include "two.h" 10 #ifndef _two_h_11 #define _two_h_12//#include "one.h" #ifndef _one_h_15 #define _ONE_H_16 void One (); #end If20 (); #endif

The 7th line of section 2~ is caused by the # include "One.h", and the 23rd line of section 10~ is caused by the # include "Two.h". After the preprocessing of the compilation, it becomes:

1 void One (); 2 void ();

Dark Horse programmer--C Language macros

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.