• fluckx@lemmy.world
    link
    fedilink
    arrow-up
    12
    arrow-down
    1
    ·
    edit-2
    8 months ago
    p = 1
    
    x = ++p
    // x = 2
    // p = 2
    
    p = 1
    x  = p++
    // x = 1
    // p = 2
    

    ++p will increase the value and return the new value

    p++ will increase the value and return the old value

    I think p = p + 1 is the same as p++ and not as ++p. No?

    • Tyoda@lemm.ee
      link
      fedilink
      arrow-up
      10
      ·
      edit-2
      8 months ago

      In C an assignment is an expression where the value is the new value of what was being assigned to.

      In a = b = 1, both a and b will be 1.

      a = *(p = p + 1)
      

      is the same as

      p += 1
      a = *p
      

      , so ++p.

      • fluckx@lemmy.world
        link
        fedilink
        arrow-up
        2
        arrow-down
        1
        ·
        8 months ago

        What I meant was:

        In the screenshot it said x = *(++p) and iirc that is not the same as saying x = *(p++) or x = *(p += 1)

        As in my example using ++p will return the new value after increment and p++ or p+=1 will return the value before the increment happens, and then increment the variable.

        Or at least that is how I remember it working based on other languages.

        I’m not sure what the * does, but I’m assuming it might be a pointer reference? I’ve never really learned how to code in c or c++ specifically. Though in other languages ( like PHP which is based on C ) there is a distinct difference between ++p and (p++ or p+= 1)

        The last two behave the same. Though it has been years since I did a lot of coding. Which is why I asked.

        I’ll install the latest PHP runtime tonight and give it a try xD

      • fluckx@lemmy.world
        link
        fedilink
        arrow-up
        3
        arrow-down
        1
        ·
        8 months ago

        Yes.

        p++ == p+= 1 == p = p + 1 are all the same if you use it in an assignment.

        ++p is different if you use it in an assignment. If it’s in its own line it won’t make much difference.

        That’s the point I was trying to make.

        • SpaceNoodle@lemmy.world
          link
          fedilink
          arrow-up
          5
          ·
          8 months ago

          No.

          ++p returns incremented p.

          p += 1 returns incremented p.

          p = p + 1 returns incremented p.

          p++ returns p before it is incremented.