From 7e0f021a9aec35fd8e6725e87e3313b101d26f5e Mon Sep 17 00:00:00 2001 From: Tobias Klauser Date: Sun, 27 Jan 2008 11:37:44 +0100 Subject: Initial import (2.0.2-6) --- .../CPLUSPLUS/CONCEPT/reference_variable.html | 167 +++++++++++++++++++++ 1 file changed, 167 insertions(+) create mode 100644 reference/CPLUSPLUS/CONCEPT/reference_variable.html (limited to 'reference/CPLUSPLUS/CONCEPT/reference_variable.html') diff --git a/reference/CPLUSPLUS/CONCEPT/reference_variable.html b/reference/CPLUSPLUS/CONCEPT/reference_variable.html new file mode 100644 index 0000000..f907323 --- /dev/null +++ b/reference/CPLUSPLUS/CONCEPT/reference_variable.html @@ -0,0 +1,167 @@ + + +Reference variables + + + +
+

Reference Variables.

+
+

+Reference variables allow two variable names to address the +same memory location. The following example shows the +technique in its simplest form. + +

+

+ + + + +
+
+        
+    #include 
+    
+    main()
+    {
+        int var1;
+        int &var2 = var1;       // var2 is a reference variable.
+
+        var1 = 10;
+    
+        cout << "var1 = " << var1 << endl;
+        cout << "var2 = " << var2 << endl;
+    }
+
+
+
+

+ + +Generally, you would not use a reference variable +in this way. Its more likely that they would be used +in function parameter lists to make the passing of +pointers more readable. +

+This gives C++ the ability to provide a +different approch to changing a variable from within a +function. Consider the two following programs. + +

+

+ + + + + + +
+
+
+    #include <stdio.h>
+
+    void Square(int *pVal);
+
+    main()
+    {
+        int Number=10;
+
+        printf("Number is %d\n", Number);
+
+        Square(&Number);
+
+        printf("Number is %d\n", Number);
+    }
+
+    void Square(int *pVal)
+    {
+        *pVal *= *pVal;            
+        
+        printf("Number is %d\n", *pVal);
+    }
+
+
+
+
+
+    #include <stdio.h>
+
+    void Square(int &Val);
+
+    main()
+    {
+        int Number=10;
+
+        printf("Number is %d\n", Number);
+
+        Square(Number);
+
+        printf("Number is %d\n", Number);
+    }
+
+    void Square(int &Val)
+    {
+        Val *= Val;
+        
+        printf("Number is %d\n", Val);
+    }
+
+
+
+
+

+ +The program on the right should be clearer to read +because you do not need to worry about pointer +dereferencing. + +


+

Examples:

+o +Example program. +

+ + +o +Example C program. + + +


+

See Also:

+ +
+
+ +

C References

+

+o +data types. + + + +


+

+

+ + + + +
+Top + +Master Index + +Keywords + +Functions +
+
+

+


+ +
Martin Leslie +29-Sep-96

+ + + -- cgit v1.2.3-54-g00ecf