Thread: reference

  1. #1
    Registered User
    Join Date
    Aug 2005
    Posts
    266

    reference

    references,, if i make a reference..does that mean that all im doing is making something that shares the same address? this isnt clearly stated in any tutorials im doing


    Code:
    int  var;
    int &ref = var;

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Yes.

    Code:
    #include <iostream>
    
    int main (void) {
        int  var = 42;
        int& ref = var;
        
        std::cout << "Address of var: " << &var
                  << "\nAddress of ref: " << &ref
                  << "\n\nValue of var: " << var
                  << "\nValue of ref: " << ref;
        return 0;
    }
    
    
    /*
    Address of var: 0x22ff74
    Address of ref: 0x22ff74
    
    Value of var: 42
    Value of ref: 42
    */
    Last edited by whiteflags; 06-01-2006 at 08:16 PM.

  3. #3
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    And is of the same type, yes.

    That way you could use ref and var from your example interchangeably.

    References are most often used in functions to take an object as an arguement, without making a copy of it.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  4. #4
    Hardware Engineer
    Join Date
    Sep 2001
    Posts
    1,398
    Right.

    The most common use of references is when function must change more than one variable. Most beginning books will show a Swap(X,Y) example, where the function swaps the X & Y values. In order to do that, you need to use references or pointers.

    It's often useful to pass a reference to an array or structure into a function so that your function can change any of the variables in the array/structure.

    Pointers and references both allow a function to "get to" the actual variable in memory. The syntax for references is simpler than pointers. And when you have a choice, references are generaly preferred over pointers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Getting an error with OpenGL: collect2: ld returned 1 exit status
    By Lorgon Jortle in forum C++ Programming
    Replies: 6
    Last Post: 05-08-2009, 08:18 PM
  2. Undefined Reference Compiling Error
    By AlakaAlaki in forum C++ Programming
    Replies: 1
    Last Post: 06-27-2008, 11:45 AM
  3. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  4. C OpenGL Compiler Error?
    By Matt3000 in forum C Programming
    Replies: 12
    Last Post: 07-07-2006, 04:42 PM
  5. c++ linking problem for x11
    By kron in forum Linux Programming
    Replies: 1
    Last Post: 11-19-2004, 10:18 AM