# 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 <iostream.h>

        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:

Example program.

Example C program.

## See Also:

## C References

data types.

Top | Master Index | Keywords | Functions