Reference variables allow two variable names to address the same memory location. The following example shows the technique in its simplest form.
| 
        
    #include  | 
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.
 Example program.
Example program.
| Top | Master Index | Keywords | Functions |