Basic C programmming Question !

Discussion in 'Programming' started by rohitink, Feb 20, 2012.

  1. #1
    Can anybody please explain me that, why is the output of this program - 7 7 9 49 ???

    Please give me a somewhat detailed explanation....
    Thanks.

    # define PRODUCT(x) (x*x)
    int main()
    {
        int i=3,j,k,l;
        j = PRODUCT(i+1);
        k = PRODUCT(i++);
        l = PRODUCT(++i);
        
        printf("%d %d %d %d",i,j,k,l);
    
    Code (markup):
     
    rohitink, Feb 20, 2012 IP
  2. sarahk

    sarahk iTamer Staff

    Messages:
    28,830
    Likes Received:
    4,541
    Best Answers:
    123
    Trophy Points:
    665
    #2
    homework?

    I think the point is for you to mess about with it and understand what the i+1, i++, ++1 operations are doing.
     
    sarahk, Feb 20, 2012 IP
  3. rohitink

    rohitink Active Member

    Messages:
    370
    Likes Received:
    6
    Best Answers:
    0
    Trophy Points:
    60
    #3
    Firstly, No Homework.Secondly, Yea i pretty much know how i+1, I++, etc works... i think i am unable to get how the operator expands.
     
    rohitink, Feb 21, 2012 IP
  4. sufalamtech

    sufalamtech Peon

    Messages:
    116
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Do this type of query solution with the help of google.
     
    sufalamtech, Feb 21, 2012 IP
  5. sarahk

    sarahk iTamer Staff

    Messages:
    28,830
    Likes Received:
    4,541
    Best Answers:
    123
    Trophy Points:
    665
    #5
    I don't know C but I'd have thought the answers would be 5, 16, 9, 16


    to find out what is going out repeat the printf between operations to see how the numbers are being manipulated
     
    sarahk, Feb 21, 2012 IP
  6. Ultrabooked

    Ultrabooked Peon

    Messages:
    26
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #6
    You aren't exactly right about that.
    Your code should work fine but it doesn't. I think that the problem is in the definition of PRODUCT(). Try defining it it in the regular way you define a function:
    int Product(int x) {...}
    Code (markup):
    not with #DEFINE.
     
    Ultrabooked, Feb 21, 2012 IP
  7. ker

    ker Peon

    Messages:
    97
    Likes Received:
    0
    Best Answers:
    1
    Trophy Points:
    0
    #7
    Hi!
    You can imagine i++ and ++i as functions that take i as parameter and return some value.
    • i++ returns i and then increments i
    • ++i increments i and returns new value
     
    ker, Feb 22, 2012 IP
  8. Rukbat

    Rukbat Well-Known Member

    Messages:
    2,908
    Likes Received:
    37
    Best Answers:
    51
    Trophy Points:
    125
    #8
    Listen to Ultrabooked. You may understand ++i, but you evidently don;'t understand how it works in a define.
     
    Rukbat, Feb 25, 2012 IP