Why this program outputs 225 istead of 1 ?

Discussion in 'C' started by lionaneesh, Mar 30, 2010.

  1. lionaneesh

    lionaneesh Active Member

    Joined:
    Mar 21, 2010
    Messages:
    848
    Likes Received:
    224
    Trophy Points:
    43
    Occupation:
    Student
    Location:
    India
    Code:
    #include<stdio.h>
    #define SQR(x) x * x
    
    int main()
    {
    
        printf("%d", 225/SQR(15));
    
    }
    why this program outputs 225 instead of 1 (according to calculation).
     
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    Precedence is not working as you expect with the MACROS.

    Try
    Code:
    printf("%d", 225/(SQR(15)));
     
  3. karthigayan

    karthigayan New Member

    Joined:
    Feb 19, 2010
    Messages:
    33
    Likes Received:
    0
    Trophy Points:
    0
    The macro is substituted like the following ,

    Code:
    #include<stdio.h>
    #define SQR(x) x * x
    int main()
    {
    
        printf("%d", 225/15*15);
    
    }
    
    Because of the operator precedence 225/15 executed first and have the result 17 .Then the 17 multiplied by 15 .So the result is 225.So use parenthesis .
     
  4. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,009
    Likes Received:
    203
    Trophy Points:
    63
    Occupation:
    Senior Support Engineer
    Location:
    England
    Better to use parentheses in the macro so that the macro can be used "normally". You wouldn't normally have to bracket a subexpression so requiring the programmer to remember for SQR that they have to do
    Code:
    225/(SQR(15))
    
    will lead to bugs because you don't remember stuff like this.

    So define the macro as
    Code:
    #define SQR(x) ( (x) * (x) )
    
    so that it can be used normally, i.e.
    Code:
    225/SQR(15)
    225/SQR(7+8)
    
    etc.
    The brackets around the individual x's mean you can put subexpressions into SQR. Without them, the second would be substituted as:
    Code:
    225/(7+8*7+8)
    
    Of course you always have to be very careful with side effect operators. This won't have the expected result:
    Code:
    int i=15;
    int j=225/SQR(i++);
    
    What's i? 16? Nope. No amount of bracketing will fix this, which is why we make macros upper case. And relying on this is definitely a bad idea, cos if some smart alec rewrites SQR as
    Code:
    #define SQR(x) (pow((x),2))
    
    then i will be 16 and not 17 as you expected.
     
    Scripting likes this.

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice