Programmingoneonone is known for sharing best programming knowledge.

Reference variable in c++ programming

in this post, you will learn about the reference variable in c++ programming and learn why we use the reference variable in computer programming.

reference variable in c++ programming, learn c++ programming
learn c++ programming

Reference variable:

to create two variables for the same memory location we use the reference variable.

                int a=10;

Note: here a is variable or type int and it's store value 10 at some location. so how we create a reference variable of variable a.
to create the reference variable of any type of variable we need to use & ampersand sign.

            <return-type> <&name-of-reference-variable> = <name-of-variable>;

Note: do not forget to use & ampersand sign with the name the reference variable.

                int a=10; 
assume that the memory location for a is 1024 and at this location 10 is stored.

reference variable for a:

int &ref= a;

Note: the return type of reference variable and the return type of the normal variable is always the same. here the value of ref variable and the value of a variable is the same(10). and the location for the ref and a variable is also same, means reference variable and normal variable refer to the same memory location.
now we can use the ref variable instant of a variable.

More on the reference variable:

  • a reference variable is not always null, we need to initialize the value to the reference variable at the definition time. 
  • we don't create an array of the reference variable.
  • to create two reference variable for one memory location we need to use a reference variable.

Example program for reference variable:

          #include <iostream>

          int main()

           int a=10;  // normal variable
           int &ref=a;  // reference variable
           std::cout<<"\n value of a is:"<< a;
           std::cout<<"\n value of reference variable is:"<< ref;
           std::cout<<"\n address of a variable is:"<< &a;
           std::cout<<"\n address of a reference variable is:"<< &ref;

           return 0;


So, I think now you fully understood what is reference variable and how to use the reference variable in c++ programming.

"please share this post as much as you can and also comment me your queries and questions related to this topic."

No comments:

Post a Comment