Define macros like defining "functions"

Source: Internet
Author: User

You can use macros to define "functions" without return values ". For example:

 
# Define printmax (A, B)/do/{/INT x = A, y = B;/printf ("MAX: % d/N", x> Y? X: Y); //} while (0) //... printmax (3, 4 );

Such a "function" is essentially different from a function in the true sense, because a macro is a pre-compilation behavior and only replaces the text before compilation. In Python source code, we often see macro definitions similar to the following:

 
# Define Foo (X)/do {/.../} while (0)

Why do I need to use the do {...} while (0) syntax instead of using {} directly? After defining the macro above, we canCodeUse code like this: Foo (3); pay attention to the end of the semicolon, it looks like a function, implement it to represent a statement. If you use {} to replace do {...} while (0), the use of semicolons is obviously a syntax error.

When using macros, pay special attention to the following points:

    • Pay special attention to spaces.The two macros below are the same:
 
# Define Foo (x) (x <2) # define BOO (x) (x <2) // note the space before the parentheses
    • There is a big difference between retrieving aliases for types using macros and typedef.For example:
 # define int * int P1, P2; // P1 is a pointer, P2 is an int variable typedef int * int; int P1, P2; // P1 and P2 are pointers // ----------------------------------------------------- # define long longunsigned long V1; // V1 is an unsigned long variable typedef long; unsigned long V1; // Error ~~~ 

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.