Square of a number being defined using #define

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

    define is just a text macro

    main()
    {
          int i,j;
          i=4/ 4 * 4;  // 1 * 4
          j=64/4 * 4; // 16 * 4
          printf("\n %d",i);
          printf("\n %d",j);
          printf("\n %d",square(4));
          getch();
    }
    
    0 讨论(0)
  • 2020-11-27 08:16

    It's a macro! So it returns exactly what it substitutes.

    i = 4/4*4;   Which is 4...
    j = 64/4*4;   Which is 16...
    

    Try this for your macro:

    #define square(x) ((x)*(x))
    
    0 讨论(0)
  • 2020-11-27 08:17

    Operator precedence is hurting you.

    The macro is expanded by the pre-processor such that

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

    which is equivalent to:

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

    j = 4/square(4) == 4/4*4 == 1*4 == 4

    0 讨论(0)
  • 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;-).

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

    When you write i=4/square(4), the preprocessor expands that to i = 4 / 4 * 4.
    Because C groups operations from left to right, the compiler interprets that as i = (4 / 4) * 4, which is equivalent to 1 * 4.

    You need to add parentheses, like this:

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

    This way, i=4/square(4) turns into i = 4 / ((4) * (4)).
    You need the additional parentheses around x in case you write square(1 + 1), which would otherwise turn into 1 + 1 * 1 + 1, which is evaluated as 1 + (1 * 1) + 1, or 3.

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