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

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

    Both / and * operators have the same precedence. To execure 3*3*3 first, you shoudl enclose them in parenthesis.

    #include <stdio.h>
    
    #define CUBE(p) p*p*p
    
    int
    main ()
    {
      int k;
      k=27/(CUBE(3));
      printf("%d",k);
      return 0;
    }
    
    0 讨论(0)
  • 2020-12-11 18:19

    When you do macros, you have to be careful about how you place parentheses. In this case, you don't have any, so the expression becomes 27/3*3*3, which by the precedence rules of / and * becomes (27/3)*3*3.

    0 讨论(0)
  • 2020-12-11 18:24
    k=27/CUBE(3);  =>   k=27/3 * 3 * 3;
    

    Do you see it? CUBE should be defined like this instead:

    #define CUBE(p) ((p)*(p)*(p))
    
    0 讨论(0)
  • 2020-12-11 18:24

    27/3*3*3 = 9*3*3 = 81 ?

    0 讨论(0)
  • 2020-12-11 18:24

    its the way in which the associativity and precedence of operators is implemented. when the expression is expanded it becomes 27/3*3*3 and not 27/(3*3*3) now, division and multiplication both have the same precedence in C but the associativity is left to right for both. so it can be shown as : (27/3)*3*3 which in turn equals (9*3)*3 = 81 also, if u remember the old arithmetic rule of BODMAS(Bracket Off Division Multiplication Addition Subtraction), this is the order of precedence, then we do division first and then multiplication. so again we get answer as 81 for 27/3*3*3.

    0 讨论(0)
  • 2020-12-11 18:25

    The preprocessor merely substitutes

    CUBE(3)
    

    with

    3*3*3
    

    So you end up with:

    k=27/3*3*3
    

    Which, evaluated left-to-right with operator precedence, is in fact 81.

    If you add parenthesees around the macro, you should find the results are correct:

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

    It would be even better to surround each instance of p with parenthesees as well, as in:

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

    Which will allow you to pass expressions to the macro correctly (for example, 1 + 2).

    0 讨论(0)
提交回复
热议问题