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 ~~~