some error in output in using macro in C

后端 未结 3 1579
面向向阳花
面向向阳花 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: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

提交回复
热议问题