Using macro results in incorrect output when used as part of a larger math expression - why does this happen?

前端 未结 13 2124
别那么骄傲
别那么骄傲 2020-12-11 17:50

This is a normal C routine program which i found out in some question bank. It is shown below:

#define CUBE(p) p*p*p

main()
{
    int k;
    k = 27 / CUBE(3         


        
13条回答
  •  生来不讨喜
    2020-12-11 18:35

    Because macros are a textual substitution, that works out to:

    k = 27 / 3 * 3 * 3;
    

    Since multiplication and division happen left to right, that works out to:

    k = ((27 / 3) * 3) * 3;
    

    So, you want to change that in two ways:

    #define CUBE(p) ((p)*(p)*(p))
    

    The outer parentheses cause the multiplications to be done before any other operations.

    The parentheses around the individual p's are for the case where you do:

    CUBE(1 + 2);
    

    Without those inner parentheses, operator precedence will trip you up.

提交回复
热议问题