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

前端 未结 13 2098
别那么骄傲
别那么骄傲 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:27

         #define CUBE(p) p*p*p
         main()
         {
            int k;
            k=27/CUBE(3);
            printf("%d",k);
    
         }
    

    As per my understanding and knowledge the value of K should be 1 as CUBE(3) would be replaced by 3*3*3 during preprocessing

    YES

    and after the subsequent compilation it would be giving the value of 1,but instead it has shown the value of 81 which has made me curious to know how it happenned.

    NO,

    k= 27/3*3*3 
    
     =(((27/3)*3)*3) (The precedence of `*` and `/` are same but the associativity is from left to right)
     =((9*3)*3) =81
    

    Replace #define CUBE(p) p*p*p with #define CUBE(p) ((p)*(p)*(p))

提交回复
热议问题