Macro usage, use

Source: Internet
Author: User

Macro usage, use
Preface

Macros play a major role in C/C ++.

Keywords

 

Several Functions of macros

1. Define Constants

2. Define an expression

3. Simplify tedious code

4, as the identifier

5. variable parameters

6, # And #

 

1. Define Constants

For example, you can use a macro to define the PI value.

#define PI    3.1415927

2. Define an expression

#define MAX(a, b)    (a>b?a:b)

3. Simplify tedious code

This can simplify some repeated code, such as declaring a function, defining member variables of a class, or simplifying the compilation of highly repetitive code multiple times.

Simplify function declaration. Some necessary keywords need to be written during function declaration, but they are the same in many cases. You can use macros to simplify function declaration.

Define thread Functions

unsigned __stdcall ThreadFunc(void* pArguments)

Can be simplified

#define THREAD_FUNC(func)    unsigned __stdcall func(void* pArguments)THREAD_FUNC(ThreadFunc){    printf("hello\n");    return 0;}

 

To define the member variables of a class, you may need to define the get and set functions of the member variables. In this case, you can use macros to simplify this process.

#define PROP_DECL(ClassName, Prop)    \    public: ClassName Get##Prop(void){return m_##Prop;}\    public: void Set##Prop(ClassName vl){m_##Prop = vl;}\    private: ClassName m_##Prop;class CTestObj{    PROP_DECL(int, Count)public:    CTestObj();    ~CTestObj();};

After the code is pre-compiled, the GetCount and SetCount functions and m_Count private member variables are generated.

It simplifies the tedious code and requires two lines of code when the memory is released.

WA *pa = new WA(c);delete pa;pa = NULL;

You can use macros to simplify this process.

#define MEM_FREE(x)    do \{\    delete x;\    x = NULL;\} while (0)WA *pa = new WA(c);MEM_FREE(pa);

Macros are widely used in ATL and MFC to simplify code.

4. ID

Macros used as identifiers are widely used.

# Ifndef _ TMP_H _ // determine whether the macro has been defined. If not, the following code will be executed, it is used to avoid repeated inclusion of # define _ TMP_H _ // definition Macro when the file is contained, so that the following definition is not executed for the second inclusion of this header file // to determine whether it is UNICODE, defines the character type of TTCHAR. # Ifdef UNICODE typedef wchar_t TTCHAR; # elsetypedef char TTCHAR; # endif // macro definition used for identification # define IN # define OUT # endif //! _ TMP_H __

 

4. variable parameters

Macros can have parameters, and the number of parameters can be variable.

#define LOG(format, ...)    printf(format, __VA_ARGS__)LOG("hello, %d, %s\n", 10, "nihao");

5, # And # usage

# The function is to convert macro parameters into strings.

# Define STR (s) # sprintf (STR (hello); // output string "hello"

# Paste macro parameters. For example, refer to the Code in the third point.

 

Notes for using macros

Macros are replaced by stored text during preprocessing. During preprocessing, no syntax is performed on the macros, but there are parentheses and few semicolons, therefore, some strange errors may occur, so use them with caution.

1. algorithm priority

A multiplication macro

#define MUL(x, y)    (x * y)

MUL (2, 3) has no problem. If MUL (1 + 2, 3) has an accident, the macro will be replaced with 1 + 2*3, the result is different from the Expected One.

In this case, you need to change the macro definition

#define MUL(x, y) (x) * (y)

2. Semicolons

#define SKIP_SPACES(p, limit)  \     { char *lim = (limit);         \       while (p < lim) {            \         if (*p++ != ' ') {         \           p--; break; }}}

If the above code is used in the judgment statement

if (*p != 0)   SKIP_SPACES (p, lim);else ...

The compiler reports an error. if is required before else, the following code can be used to solve the problem:

#define SKIP_SPACES(p, limit)     \     do { char *lim = (limit);         \          while (p < lim) {            \            if (*p++ != ' ') {         \              p--; break; }}}          \     while (0)

This method is widely used in linux.

 

3. Repeated calls

#define min(X, Y)  ((X) < (Y) ? (X) : (Y))

If this is the case when calling

int x = 1;int y = 2;min(x++, y);

After expansion, x ++ is called twice. This method should be avoided.

 

4. Recursive reference of itself

The macro definition is as follows:

#define foo (4 + foo)

According to the previous understanding, (4 + foo) is expanded to (4 + (4 + foo), and continues until the memory is exhausted. However, the Preprocessor only expands once. That is to say, foo is only expanded to (4 + foo), and the meaning of foo is determined based on context.

For the following cross references, the macro will only be available once.

#define x (4 + y)#define y (2 * x)

X is expanded into (4 + y)-> (4 + (2 * x), and y is expanded into (2 * x)-> (2*(4 + y )).

Note that this is not recommended, and the program is very readable.

 

5. Macro parameter preprocessing

If the macro parameter contains another macro, the macro parameter will be fully expanded before it is substituted into the macro, unless the macro contains # Or ##.

The macro definition is as follows:

#define AFTERX(x) X_ ## x#define XAFTERX(x) AFTERX(x)#define TABLESIZE 1024#define BUFSIZE TABLESIZE

AFTERX (BUFSIZE) is expanded to X_BUFSIZE. Because the macro contains #, macro parameters are directly substituted into the macro.
XAFTERX (BUFSIZE) is expanded to X_1024. Because the macro of XAFTERX (x) is AFTERX (x) and does not exist # Or #, The BUFSIZE is fully expanded to 1024 before it is substituted into the macro and changed to X_1024.

 

Macros are replaced during preprocessing. Therefore, macros or macro variable names are not displayed during actual compilation.

 

Refer:

Http://hbprotoss.github.io/posts/cyu-yan-hong-de-te-shu-yong-fa-he-ji-ge-keng.html

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.