A simple way to customize macros in C + + _c language

Source: Internet
Author: User

You can use a macro to define a function that has no return value. For example:

Copy Code code as follows:
#define PRINTMAX (A, b) \ do \ {\ int x = A, y = b; \ printf ("Max:%d\n", x > y x:y); \} while (0)// ... Printmax (3, 4);

Such "functions" are essentially different from functions in real sense, because a macro is a compile-time behavior that replaces text only before it is compiled. In the Python source code, you can often see a macro definition similar to the following:

 #define FOO (x) \ Do {\  ... \} while (0) 

Why use the syntax such as do {...} while (0) without directly using {}? By defining the above macro, we can use code like this in the Code: Foo (3); Note the semicolon at the end, which looks like a function, and implements it to represent a statement.  If you use {} instead of Do {...} while (0), it is obviously a grammatical error to use a semicolon.

When working with macros, there are a few things to pay special attention to:

Pay special attention to spaces. The following two macros are the same:

 #define FOO (x) (x << 2) #define BOO (x) (x << 2)//Note the spaces preceding the brackets 

Using a macro to alias a type is a big difference from a typedef. For example:

Copy Code code as follows:
#define INT int * int p1, p2; P1 is a pointer, p2 is an int variable typedef int * INT; INT P1, p2; P1, p2 are pointers//---------------------------------------------------#define LONG long unsigned long v1; V1 is an unsigned long variable typedef long long; unsigned LONG v1; Wrong Oh ~ ~ ~

Related Article

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.