Summary of C Language Macros

Here are some tips for C language macros to fill in the gaps.

Macro Expansion Errors

#define FUN(x) 1 + x * x
int main()
{        
    printf("%d\n", 3*FUN(1));        
    return 0;
}

The macro expands to <span>3*1+1*1</span>, not <span>3*(1+1)</span>. To avoid this kind of error, always use parentheses in macros.<span>#define FUN(x) (1 + x * x)</span>

Internal Macro Expansion Errors

#define FUN(x) (x*x)
int main()
{
    printf("%d\n", FUN(1+1));
    return 0;
}  

The macro expands internally to (1+11+1), not ((1+1)(1+1)). To avoid this error, always add parentheses around macro variables.<span>#define FUN(x) ((x)*(x))</span>

Macro Variable Increment/Decrement Errors

#define FUN(x) (x*x)
int main()
{        
    int i=2;        
    printf("%d\n", FUN(i++));        
    return 0;
}

The output here is 6, which is 2*3, because i was incremented. To avoid this error, do not use increment/decrement in macro expansions.

Macro Function Expansion Errors

#define FUN(x) x=10;x+=1
int main()
{        
    int i=2;        
    if (i == 1)                
        FUN(i);        
    printf("%d\n", i);       
    return 0;
}

Here, because the if statement lacks braces, the macro expansion causes x+=1 to be outside the if statement. Thus, the output is 3 instead of 2. To avoid this error, you can use the do-while structure as follows:<span>#define FUN(x) do{x=10;x+=1;}while(0)</span>

References:

“In-depth C Language and Program Operation Principles”

Just enjoy it~

Leave a Comment