Code About Us Tutorial


  Pointers and References
    What are Pointers?
    Declaring Pointers
    The Indirection and Dereference operator
    What is a Reference?
    Using References
    Using Pointers and References
    The new Keyword
    The delete Keyword
    Passing By Reference
    Passing by Value


   
 

Home > Pointers and References > Using References

November 27, 2009 1:48 pm

   

Using References

Let me give you an example showing the reference at work.

 

 
#include <iostream.h>

int main() {

int Money = 900; //creates variable Money int& rMoney = Money; //creates reference to Money int n; //variable for input

cout <<"Here is the current amount: " << "$" << Money << "n"; cout <<"Enter how much money you wish to withdraw." << endl; cin >> n;

cout <<"Taking out " << "$" << n << endl; cout <<"Here is the money you have left: " << "$" << rMoney - n << endl; return 0; }

In this program, I prompt the user to enter how much money they wish to withdraw. Once the input was captured, I used the reference and the input variable to find out how much money they have left, simply by writing rMoney – n, which is really 900 – n. Remember that the reference is just as if you were writing the actual thing. So rMoney held the value 900 because the original variable was set to 900. Please Rate this Code:


    Comments for: Using References
Annonymouse User says:
what's the use ??? we can just do (money - n)

why use a reference???





Add Comment:
Name:
Email:


 «