Macro alternative solution in C ++

Source: Internet
Author: User
Tags constant definition define null

Macro alternative solution in C ++

Macro is a god in the C language and can play with various tricks. It is also because of this that it will cause a lot of troubles to ordinary programmers. Since macros only work in the pre-compilation phase, the compiler cannot detect the bugs. As a new C ++ programmer, it is better to stay away from them.

C ++ provides some alternative solutions for macros.

 

1. Constant Definition

# Deprecision num 100

This macro is discussed in the first clause of license tivec ++. Since macros are pre-compiled programs for processing, the num name is not added to the symbol table. If a compilation error occurs, the system prompts that the num is not displayed, but 100, added additional obstacles to troubleshooting errors.

The alternative is to use const to define constants or enum.

Const int num = 100;

The const constant is placed in the header file, and there is no need to worry about the problem of multiple instances. For the const modified variables, the compiler will generally optimize them without the problem of multiple definitions.

 

The C language also has a special constant definition: null. The general definition is # define null 0, and the pointer content is an integer, which is unreasonable. Therefore, null is replaced by nullptr in C ++ 11.

 

2. Function Definition

Since macros only replace and expand strings in the code, macro-defined functions do not actually reduce the size of the Code. In addition, there are some natural defects. Assume that a function macro is used to calculate the square.

# Definesquare (x) (x * X) voidf (double D, int I) {square (d); // oksquare (I ++); // bad, (I ++ * I ++) Square (D + 1); // worse, (D + 1 * D + 1 )}

Even if we can solve the problem by adding brackets to the parameter # define square (x) * (x), the problem still cannot be solved when I ++ is executed twice.

The alternative in C ++ is to use the inline function.

inline int square(intvalue){    return value*value;}

Inline functions have the nature of functions. parameters are not repeatedly calculated for passing a value or passing a reference. At the same time, the type of parameters is checked to ensure the correctness of the Code; the inline function also expands the code in the code, and the efficiency is not inferior to the macro.

If the integer type does not meet the requirements, you can also define it as a template:

template<classT>inline T square(T& value){    return value*value;}

There is also a more outrageous form of Function Definition:

#defineNull_Check(p)\if(p == NULL) return;

This type of function is defined by the backslash. Note that if a space is added after the backslash, Some compilers may encounter a mutation error and prompt information, you may be troubled for a long time. Because the backslash will make sense of the space character, it will introduce illegal characters in the code, and it is difficult for human eyes to find such errors.

 

3. Type redefinition

# Definedword unsigned int

This type of redefinition can be replaced by typedef unsigned int DWORD.

 

4. Conditional compilation

#ifdefSystemAtestA();#else//SystemBtestB();#endif

 

This type of Conditional compilation macro usually occurs when the same set of code is used on different products or platforms. When systema is defined, the systemb code is not compiled, which means that your code is not always monitored by the compiler. You can use the template technology to solve the problem.

 

Constint extends EMA = 1; constint systemb = 2; Template <int T> void test () {}// defines the special version template of different systems <> void test <extends EMA> () {// systema Implementation} template <> void test <systemb> () {// systemb Implementation}

In this way, different systems can use their own templates, and other people's code will also be checked by the compiler, so as not to miss the compilation error.

 

5. the header file contains

# Ifndeftest_h # Implementation of definetest_h // test. h # endif

To prevent repeated inclusion of header files, C ++ can only do so now. There is no alternative. Looking at the original committee, Bjarne stroustrup provides an include design in the book "design and evolution of C ++ language". Unfortunately, it is not actually implemented. (CPP, C language Preprocessor)

I have suggested adding an include indicator to C ++ as a replacement for # include of CPP. The include of C ++ can be different from the # include of CPP in the following three aspects:

1) if a file is included twice, the second include will be ignored. This solves a practical problem. Currently, this problem is handled in a very inefficient and clumsy way through # define and # ifdef.

2) macros defined outside the body of the include statement are not expanded within the body of the include statement. This provides a mechanism to isolate information so that the information is not disturbed by macros.

3) The macro defined in the body of include is not expanded in the body processing after the body of include. This ensures that the macros in the include body do not contain the compilation unit which is strongly dependent on the order, and generally prevents the strange situation caused by macros.

For systems that use pre-compiled header files, this mechanism will be a boon to those who need independent software combinations. Note that in any case, this is just an idea, not a language feature.

 

That is to say, this idea is not implemented in C ++.

 

If you don't have a good grasp of macros, you can stay away.

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.