some error in output in using macro in C

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

提交回复
热议问题