Open In App

Can References Refer to Invalid Location in C++?

Improve
Improve
Like Article
Like
Save
Share
Report

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.


Last Updated : 07 Jan, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads