Square of a number being defined using #define

后端 未结 11 1134
说谎
说谎 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:30

    Because of operator precedence in the expression after the preprocessor - you'll need to write

    #define square(x) (x*x)
    
    0 讨论(0)
  • 2020-11-27 08:31
    i=4/square(4);
    

    expands to

    i=4/4*4; 
    

    which equivalent to

    i=(4/4)*4;
    
    0 讨论(0)
  • 2020-11-27 08:33

    That's because the compiler replaces it with:

    i=4/4*4; 
    j=64/4*4;
    

    i = (4/4)*4 = 1*4 = 4.

    j = (64/4)*4 = 16*4 = 64.

    0 讨论(0)
  • 2020-11-27 08:33

    Manually expand the macro in the code, and it will be clear. That is, replace all the square(x) with exactly x*x, in particular don't add any parentheses.

    0 讨论(0)
  • 2020-11-27 08:42

    As the other answers say, you're getting burned by operator precedence. Change your square macro to this:

    #define square(x) (x*x)
    

    and it'll work the way you expect.

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