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

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

提交回复
热议问题