• ZILtoid1991@lemmy.worldOP
      link
      fedilink
      arrow-up
      7
      arrow-down
      1
      ·
      4 months ago

      The & operator references the value.

      int i;
      int* p = &i;
      

      In C++, the & at the function argument makes it a reference type (safe pointer).

      void someFunction(int& refVal) {
          [...]
      }
      
      • Flames5123@sh.itjust.works
        link
        fedilink
        English
        arrow-up
        3
        arrow-down
        2
        ·
        4 months ago

        As someone who likes working with higher level languages, I never understood the pass by reference or even referencing different pointers. It never stuck out to me as useful in what I want software to do. It’s too close to hardware.

        • Sylvartas@lemmy.dbzer0.com
          link
          fedilink
          English
          arrow-up
          10
          ·
          edit-2
          4 months ago

          Most of the time you pass by reference for more outputs, or by const ref to avoid copying a big-ass data structure (which is not always straightforward, with structures smaller than a pointer, which are pretty big in 64 bits architecture, you lose more to the ref overhead than to the copy IIRC)

          • DahGangalang@infosec.pub
            link
            fedilink
            arrow-up
            4
            ·
            4 months ago

            Another reason I commonly see: to change the structure / “main pointer” to a data structure (esp during freeing and cleanup).

        • ZILtoid1991@lemmy.worldOP
          link
          fedilink
          arrow-up
          1
          ·
          4 months ago

          Reference values are quite useful, such as:

          double valOut;
          if (parseDouble(valOut) == 0) { //Argument of parseDouble is ref type, no & needed for input, no exceptions needed for error handling
              [...] //No error, code executed normally
          } else {
              [...] //Erroreus input
          }
          
    • Dejected Warp Core@lemmy.world
      link
      fedilink
      arrow-up
      4
      ·
      3 months ago

      *x = dereference or “point to”. Treats the variable x as containing a pointer value. Evaluates to a variable existing at the address in x.

      &x = reference or “get address of”. Evaluates to the address of x.

      They’re complimentary operators, so *(&x) cancels out and is equvalent to just x.