Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

Small C Question

  • 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, Registered Users 2 Posts: 7,289 ✭✭✭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, Registered Users 2 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, Registered Users 2 Posts: 7,289 ✭✭✭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