Macro with arguments

1. The parameters of the macro

Like macro function
#define Cube (X) ((X) (X) (X))
macro can be parameterized

#define cube(x) ((x)*(x)*(x))
int main()
{
    printf("%d\n",cube(5));//125
    return 0;
}

#define cube(x) ((x)*(x)*(x))
int main()
{
    int i;
    scanf("%d",&i);
    printf("%d\n",cube(i));
    return 0;
}

2. ill-defined macro
#define RADTODEG1 (the X-) (the X-* 57.29578)
#define RADTODEG2 (the X-) (the X-) * 57.29578

#define RADTODEG1(x) (x*57.29578)
#define RADTODEG2(x) (x)*57.29578
int main()
{
    printf("%f\n",RADTODEG1(5+2));//119.591560   因为这样写变成了(5+2*57.29578
    printf("%f\n",180/RADTODEG2(1));//10313.240400   变成了180/(1)*57.29578
    return 0;
}

3. The principles of macro parameters of
everything brackets
entire value brackets to
each place parameters must appear in parentheses

#define RADTODEG2(x) ((x)*57.29578))

4 can take a plurality of parameters
#define MIN (a, b) ( (a)> (b)? (B) :( a))
may be combined (nested) use other macros

5. semicolon?
After the macro definition, do not add a semicolon

6. The use of macro parameters are common in large program code

It can be very complex, such as the function "generated"
with the aid of # ## and the two operators

There is cultural difference

Partial macroblocks are replaced inline function

7. Other preprocessor directive

Conditional compilation
error
......

Published 56 original articles · won praise 0 · Views 442

Guess you like

Origin blog.csdn.net/weixin_45087108/article/details/104535203