Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Small C Question

Options
  • 14-11-2005 12:34pm
    #1
    Closed Accounts Posts: 1,541 ✭✭✭


    Hi Forum,

    Small question for someone into c programming. Some code:
    for( count = (N - 2 * ofs); count > 0L; count-- )
            facc += *(p++);
    

    My question relates to the line:
    facc += *(p++);
    

    p points at a an array called 'D'.

    Is the above line equal to:

    facc=facc+D[p];
    p=p+1;

    Is that the basic function of the line. The p++ is confusing me. Does it not increment straight away? Or does it increment after facc is assigned it's value?

    Many thanks for any help.


Comments

  • Registered Users Posts: 7,276 ✭✭✭kenmc


    Your intrepretation is correct. It does not increment "p" straight away as it's a "post incrementor", same as the "count--" in the line above it. if you wanted to increment p before hand you would use a "pre-incrementor" i.e. ++p;
    This sort of stuff is incredibly common in C, especially using pointers (arrays are pointers too don't forget). See how much more elegent the
    "facc += *(p++);"
    is relative to the
    "facc = facc + D[p];
    p=p+1;"

    edit: In fact, if you were to replace the facc+=*(p++); line with yours, you would in fact break the code, unless you surrounded your code with braces "{....}" as the for loop would only increment the first line (facc = facc+D[p]).
    Ken


  • Registered Users Posts: 1,865 ✭✭✭Syth


    kenmc wrote:
    "facc += *(p++);"
    is relative to the
    "facc = facc + D[p];
    p=p+1;"

    Kenmc is correct about the p++ vs ++p, however the above is incorrect.

    p points to the i-th element of D, thus p = *D + i, ie the start of D plus the index. So *p is not equal to D[p].


  • Registered Users Posts: 7,276 ✭✭✭kenmc


    Doh yeah how the hell did I miss that??? I knew what he was trying to say though so i read between the lines!
    Anyway - point proven - facc += *(p++); is nicer. :)
    so*(p+i) = D; or since initially i = 0, *p = D[0], then *p++ = D[1] the first time, D[2] the second time etc.


  • Closed Accounts Posts: 1,541 ✭✭✭finnpark


    Cheers:) .

    Thanks again Ken for info and thanks Syth for pointing out slight flaw:eek: .;)

    Am getting there now:cool: .

    Thanks Again.


Advertisement