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

前端 未结 13 2129
别那么骄傲
别那么骄傲 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条回答
  •  猫巷女王i
    2020-12-11 18:37

    C macros do textual substitution (i.e. it's equivalent to copying and pasting code). So your code goes from:

    k=27/CUBE(3);
    

    to

    k=27/3*3*3;
    

    Division and multiplication have the same precedence and have left-to-right associativity, so this is parsed as:

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

    which is 9 * 3 * 3 = 81.

    This is why C macros should always be defined with liberal use of parentheses:

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

    For more information, see http://c-faq.com/cpp/safemacros.html from the comp.lang.c FAQ.

提交回复
热议问题