当前位置:网站首页>[C language basics] macro definition usage

[C language basics] macro definition usage

2022-06-12 05:42:00 Amos-Chen

Macro definition form and use

Macro definition format

#define your_macro_name the_replacement

about #define The name of your_macro_name, It is named in the same way as the variable name , replace text the_replacement It could be any string .
Usually define Instructions take only one line , If the replaced text is long , It can be a backslash \ Line break .

Define constants

#define e 2.71828

Any text

#define forever for( ; ; )

Use macros forever

int main() {
    
    forever{
    
        printf(1);
    }
    return 1;
}

Macro definition with parameters

#define max(a,b) ((a)>(b)?(a):(b))

Use macros max

int main() {
    
    int x = max(1, 2);
    printf("%d",x);
    return 1;
}

An argument is an argument character

Formal parameters cannot be replaced by quoted strings , But if you want to pass in an argument, it is the corresponding argument character ( That is, the arguments are automatically quoted ) Well ?
For example, an argument is passed in amos( No quotation marks ), What I actually want to use is "amos"

#define dprintf("hello " #str)

Use dprint

int main() {
    
    dprint(amos);
    return 1;
}

When calling this macro , This macro is extended to :

printf( "hello " "amos")  

Equivalent to

printf( "hello amos")  

Join arguments

#define paste(name) char_##name
int main() {
    
     char paste(a);
     char paste(b);
     // char_a char_b  There is no need to define ,  The definition has been completed in the macro 
     char_a = 'x';
     char_b = 'y';
     printf("%c%c\n", char_a, char_b) ;
     return 1;
}

Multiline macro replacement

#define loop(a, b) for(int i=0;i<(b);++i)\
{
   \
(a)+=i;\
}\

loop Use of macros :


int main() {
    
    int a = 100, b = 100;
    loop(a, b);
    printf("%d\n", a);
    return 1;
}

Print as 5050

matters needing attention

Add parentheses to each shape as much as possible

#define square(x) x*x

int main() {
    
    printf("%d\n", square(1 + 5));
    return 1;
}

The above code , It feels like it should be printed 36, Not really
Because the macro is replaced with :

printf("%d\n", 1+5*1+5)

The result is 11, So add brackets as much as possible .

Cancel macro definition

#define square(x) x*x
#undef square
原网站

版权声明
本文为[Amos-Chen]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203010614150215.html