Thread: Parameters of the type pointers vs Parameters of the type reference

  1. #1
    Registered User
    Join Date
    May 2017
    Posts
    61

    Parameters of the type pointers vs Parameters of the type reference

    Hi, can anyone explain me when should i use pointers and when i should use reference ?

    Code:
    void exchange(int * pa, int * pb) {
        int temp = *pa;
        *pa = *pb;
        *pb = temp;
        cout << "\n em troca ( int * pa, int * pb), depois da troca *pa = "
                << *pa << " *pb = " << *pb << endl;
    }
    
    
    void exchange(int &a, int &b) {
        int temp = a;
        a = b;
        b = temp;
        cout << "\n em troca ( int &a, int &b), depois da troca a = "
                << a << " b = " << b << endl;
    }
    
    
    int main(int argc, char** argv) {
        int x = 2, y = 4;
        cout << "\n\n em main(), antes de troca(x,y) x= " << x << " y = " << y << endl;
        exchange(x, y);
        cout << "\n em main(), depois de troca(x,y) x= " << x << " y = " << y << endl;
    
    
        x = 2;
        y = 4;
        cout << "\n\n em main(), antes de troca(&x,&y) x= " << x << " y = " << y << endl;
        exchange(&x, &y);
        cout << "\n em main(), depois de troca(&x,&y) x= " << x << " y = " << y << endl;
        return 0;
    }

  2. #2
    Informer -Adrian's Avatar
    Join Date
    Jan 2013
    Posts
    830
    Prefer references where you can, otherwise use pointers. References cannot be re-bound to another memory location for instance.

  3. #3
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,739
    It's more complicated than how I'm about to portray it, as Adrian hinted, but I use pointers instead of references only when I want them to sometimes be nullptr. For no other reason.
    Devoted my life to programming...

  4. #4
    Registered User
    Join Date
    May 2017
    Posts
    61
    Thanks you both for your answers

    I found this video that i find useful too.

    YouTube

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Reference Parameters help
    By randyjohnson in forum C Programming
    Replies: 5
    Last Post: 10-29-2012, 08:48 PM
  2. Replies: 16
    Last Post: 08-02-2011, 12:30 PM
  3. reference parameters
    By LowLife in forum C Programming
    Replies: 8
    Last Post: 01-25-2006, 11:50 AM
  4. Using Generic Classes as Type Parameters
    By pianorain in forum C# Programming
    Replies: 2
    Last Post: 11-19-2005, 03:20 PM
  5. Type and nontype parameters w/overloading
    By Mr_LJ in forum C++ Programming
    Replies: 3
    Last Post: 01-02-2004, 01:01 AM

Tags for this Thread