The use of C++define

Source: Internet
Author: User
Tags define definition log log

When writing a program, we often encounter a problem where we need to write a lot of the same code, and the code structure is the same. Always want to encapsulate this code and then call directly, but if this code logic is not complex, and the amount of code is not suitable for encapsulation, then we will think of C + + keyword define. In fact, it is wise of you to meet the above situation and think of something else----template, and we'll talk about it later. Today, I read the relevant knowledge of C + + define, make a record.

1. What is define: macro definition, simple understanding is to replace, in fact, this is also the essence. If you are familiar with the g++ compilation process, you will learn that a concept called preprocessing is to do a process before compiling. This process is not as complex as compiling, it is simply recursive substitution and deletion. Replace the macro definition with the Include file and delete the comment. Note Here we talk about a concept, recursive substitution, which is actually very common, such as your program include a. h file, but this. h file also introduces another. h file, so this time you need to do a recursive replacement. Let's see for ourselves. What is the pre-treatment done? (to reduce the code after preprocessing we do not introduce other files)

So we can better understand the role of define and the role of pretreatment.

How to use 2.define:

    • Simple to use: Define identifier replacement-list (optional) This is the most basic way to use, as in our example above, in the preprocessing when the identifier is replaced by Replacement-list ( Optional). For example: in the development of the program will define a lot of error code, such as using 22 to indicate the success of the image upload, if we judge assert (RESULT==22). It seems to be no problem, so if you read whose code is written like this, what would you think? Who wrote that, what does this 22 mean? Then we need to give 22 aliases, for example: #define SUCCESS = 22
    • With Parameter form: In addition to the above method of use we can also be given parameters for macro definition, such as:
      #include <iostream>#include<string.h>
      Defines a macro that connects A and B#defineAppend (A, b) a+b;using namespacestd;intMainintargcChar*argv[]) { stringTest1 ="1"; stringTest2 ="2";
      Call cout for macro definition<<Append (TEST1,TEST2); return 0;}

      From this example we can see one of the benefits of macro definition: To some extent, the type of the parameters in the macro definition can be ignored, which is not similar to template, we use the template to rewrite the above code:

      #include <iostream>#include<string.h>using namespacestd;
      Define Template Method Templates<classT>t Append (t a,t b) {returnA +b;}intMainintargcChar*argv[]) { stringA ="1"; stringB ="2"; Using template methods
      cout<<Append (A, b); return 0;}

      Do we think that in this case the macro definition is consistent with the template? In fact, let's consider the following scenario, assuming that there is a macro defined as a # define Add (b) a+b, and the call procedure in code is such that A*add (A, b) *b; Can you think of the result? The answer is 5, not our expected 6, for the simple reason that this is simply a replacement, after preprocessing the result is a*a+b*b. But the result of the template operation is 6, which is the difference. So when you use it, you should consider whether to choose template or define.

    • The representation of the code snippet in define: The macro definition above is a simple statement, what if we need to define a slightly more complex statement? For example: We are accustomed to, or is a personal habit, like to make some judgment statement macro definition, for example, we do a function error code in the time we usually want to be able to separate the code and log log, so that the code is not so messy, then we will define a slightly more complex macro definition.

      #include <iostream>#include<string.h>
      Macro defines a maxname#defineMaxname 10
      The macro definition defines a condition for identifying the return code after the image has been uploaded and outputting the log condition#defineAssertreturnvalue (Name,result) do{if(result==0) cout<<"Image"<<name<<"Upload Successful";} while(0)using namespacestd;classpicture{ Public: Picture (Const Char*path,Const Char*file) {strcpy ( This-Path,path); strcpy ( This-file,file); } ~Picture () {}Private: CharFile[maxname]; Charpath[maxname];};intUploadpicture (ConstPicture picture ) {cout<<"Success"; return 0;}intMainintargcChar*argv[]) { Picture picture (" -"," -"); intresult =uploadpicture (picture);
      Call the result to determine the macro definition Assertreturnvalue (" -", result); return 0;}

      Here we should pay attention to the code snippet of the macro definition of the wording.

    • Conditional macro Definition ifdef: Compile environment can be set by # define at compile time, syntax structure:
      // different operating environments, different header files  <windows.h>#endif<linux.h>#endif

      Here's a list of common macro definitions for C + +:

    • #空指令 without any effect # # contains a source code file # define definition macro #undef cancel a defined macro # If the given condition is true, compile the following code #ifdef if the macro is already defined, compile the following code #ifndef if the macro is not defined, Compile the following code #elif if the previous # if given condition is not true and the current condition is true, compile the following code #endif end a #if... #else条件编译块#error停止编译并显示错误信息

      Reference http://www.cnblogs.com/zi-xing/p/4550246.html

The use of C++define

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.