Skip to content
Related Articles

Related Articles

Can References Refer to Invalid Location in C++?

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 07 Jan, 2022
Improve Article
Save Article

Reference Variables: You can create a second name for a variable in C++, which you can use to read or edit the original data contained in that variable. While this may not sound appealing at first, declaring a reference and assigning it a variable allows you to treat the reference as if it were the original variable for the purposes of accessing and modifying the value of the original variable—even if the second name (the reference) is in a different scope. This means that if you make your function arguments references, you’ll be able to essentially change the data given into the function. This is in contrast to how C++ generally works, in which function parameters are copied into new variables. It also helps to save time.

In C++, Reference variables are safer than pointers because reference variables must be initialized and they cannot be changed to refer to something else once they are initialized. But there are exceptions where we can have invalid references.

1) Reference to Value at the Uninitialized Pointer

int *ptr;
int &ref = *ptr; // Reference to value at 
                 // some random memory location

2) Reference to a Local Variable is Returned

int& fun()
int a = 10;
return a;

Once fun() returns, the space allocated to it on the stack frame will be taken back. So the reference to a local variable will not be valid.

Please write comments if you find anything incorrect in the above article or you want to share more information about the topic discussed above.

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!