Reference in C++ – All you need to get started!

Filed Under: C++
C REFERENCE

Hey, folks! In this article, we will be focusing on Reference in C++ in detail. So, let us begin!!


Understanding Reference in C++

C++, as a programming language, provides us with a variety of concepts to deal with static as well as dynamic allocation of data through data variables.

Reference enables the programmer to provide a particular variable with an alternative name to it. Thus, a reference can be considered as an alias name to the existing variable.

Reference thus behaves as a label to the variable pointing to the memory location of the stored value in the existing variable.

Let us now focus on the structure of C++ Reference in the upcoming section.


Syntax of C++ reference

Have a look at the below syntax!

int variable = value;
int& reference-variable = variable;

As we can see in the above command, that, we use the ampersand ‘&’ symbol to refer a new variable name to the existing variable.

Thus, the reference variable would point to the same memory location as that of the original variable.

Now, will implement the concept of reference through the examples in the below section.


Examples of reference variables

In the below example, we have created a reference for the variable ‘var’ and displayed the values.

#include<iostream> 
using namespace std; 

int main() 
{ 
int var = 100;
int& ref_var = var;
cout<<"The original variable:"<<var<<endl;
cout<<"The reference variable:"<<ref_var<<endl;


return 0; 
} 

As the reference variable points to the same memory block as that of the variable, thus, the value assigned to the ‘var’ is available using the reference variable as well.

Output:

The original variable:100
The reference variable:100

Now, we have modified the variable’s value and we can see that the modified value is reflected in the reference variable pointing to the same memory block as well.

#include<iostream> 
using namespace std; 

int main() 
{ 
int var = 100;
int& ref_var = var;

cout<<"The original variable:"<<var<<endl;
cout<<"The reference variable:"<<ref_var<<endl;

var = 20;
cout<<"Altered values....\n";
cout<<"The original variable:"<<var<<endl;
cout<<"The reference variable:"<<ref_var<<endl;

return 0; 
} 

Output:

The original variable:100
The reference variable:100
Altered values....
The original variable:20
The reference variable:20

Conclusion

By this, we have come to the end of this topic. Feel free to comment below, in case you come across any question.

Stay tuned and do visit C++ programming with JournalDev for some interesting posts regarding C++ programming.

Till then, Happy Learning!!


References

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages