some error in output in using macro in C

后端 未结 3 1578
面向向阳花
面向向阳花 2020-12-21 14:06

my code is:-

#include
#include

#define sq(x) x*x*x

  void main()
  {
    printf(\"Cube is : %d.\",sq(6+5));
    getch();
  }
         


        
相关标签:
3条回答
  • 2020-12-21 14:25

    You need parentheses around the argument.

    #define sq(x) ((x)*(x)*(x))
    

    Without the parentheses, the expression will expand to:

    6+5*6+5*6+5
    

    Which you can see why it would evaluate to 71.

    A safer solution would be to use an inline function instead. But, you would need to define a different one for each type. It might also be more clear to rename the macro.

    static inline int cube_int (int x) { return x*x*x; }
    
    0 讨论(0)
  • 2020-12-21 14:27

    Always shield your macro arguments with parenthesis:

    #define sq(x) ((x) * (x) * (x))
    

    Consider the evaluation without the parenthesis:

    6 + 5 * 6 + 5 * 6 + 5
    

    And recall that * has a higher precedence than +, so this is:

    6 + 30 + 30 + 5 = 71;
    

    Get to know the precedence rules if you don't already: http://en.cppreference.com/w/cpp/language/operator_precedence

    0 讨论(0)
  • 2020-12-21 14:39

    If you define the macro like this:

    #define sq(x) x*x*x
    

    And call it:

    sq(6+5);
    

    The pre-processor will generate this code:

    6+5*6+5*6+5
    

    Which is, due to operator precedence, equivalent to:

    6+(5*6)+(5*6)+5
    

    That's why, the macro arguments must be parenthesized:

    #define sq(x) (x)*(x)*(x)
    

    So that pre-processor output becomes:

    (6+5)*(6+5)*(6+5)
    

    However, if you pass some arguments with side-effects such as (i++):

    sq(i++)
    

    It will be expanded to:

    (i++)*(i++)*(i++)
    

    So, be careful, perhaps you need a function

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