Square of a number being defined using #define

后端 未结 11 1219
说谎
说谎 2020-11-27 08:06

I was just going through certain code which are frequently asked in interviews. I came up with certain questions, if anyone can help me regarding this?

I am totally

11条回答
  •  广开言路
    2020-11-27 08:28

    square is under-parenthesized: it expands textually, so

    #define square(x) x*x
       ...
    i=4/square(4);
    

    means

    i=4/4*4;
    

    which groups as (4/4) * 4. To fix, add parentheses:

    #define square(x) ((x)*(x))
    

    Still a very iffy #define as it evaluates x twice, so square(somefun()) calls the function twice and does not therefore necessarily compute a square but rather the product of the two successive calls, of course;-).

提交回复
热议问题