Can You Re-Assign Reference Variables in C++?🤔

To start with let us define what is meant by Reference Variable.

Reference variable is a type of variable which is regarded as an alias name to an existing variable.

Declaring a reference variable

Reference Variable
I have used a code snippet from C++ programming language
Here as you can see that I have declared a variable of type 
integer and named it as val, As soon as the compiler compiles
the statement  memory is allocated for the variable val in the stack and initialized with the value 10.
With the next statement we are creating a reference variable named ref which is referring the variable val.

This also means that there is no separate memory allocated for the variable ref whereas it is just 
another name for the memory location identified by val.

Can we Reassign it?

The next question which comes to mind is whether it is possible to reassign the reference variable to 
refer some other variable at run time for example:

Reassigning Reference Variable












In the above example I have created two integer variables val1 and val2 having their own memory 
location in stack containing values 10 and 20 respectively. I have a reference variable ref initially 
referring to val1 variable therefore when we try to print its value it will print 10.

But the twist comes when we try to reassign the reference variable to another variable val2 which holds 
the value 20 then if we try to print its value we will expect 20 to get printed. 

Code Output With Reference Variable







But whether ref is actually pointing to the variable val2? Let us check by printing the address. 

Reference variable address












OUTPUT:

Reference variable output











Conclusion:

As you can see that the address of the reference variable is same as that of the variable val1 and after 
reassigning to val2 its address did not change. So what happened here?

Actually we modified the value of the val1 to 20 by assigning ref = val2 through reference. If we 
print the value of val1 after this it will print 20.So in short reference variable cannot point to 
other variable during its lifetime.





Comments

Popular posts from this blog

Creating RESTful Minimal WebAPI in .Net 6 in an Easy Manner! | FastEndpoints

Mastering Concurrency with Latches and Barriers in C++20: A Practical Guide for Students

Graph Visualization using MSAGL with Examples