In: Computer Science
In C/C++ programming language, write down the lines of codes (and figure) to show-
a) assignment-by-sharing
b) dangling reference
Though 'assignment-by-sharing' term does not clears the aim on its own but checking the second part of dangling reference, 'assignment-by-sharing' must be assignment by sharing using reference.
Refer the lines of C++ codes below to understand :
a) Assignment-by-sharing
int main()
{
int x = 10;
int &y=x; //y is reference to x
y=30;
cout<<"x = "<<x<<endl;
x=50;
cout<<"y = "<<y<<endl;
return 0;
}
Here the output will be
30
50
This is because both x and y are sharing the same reference. Hence assigning a value to x will lead to assignment in y and vice - versa.
b) Dangling Reference
int &fun()
{
int i = 10;
return i;
}
int main()
{
int &x = fun();
cout<<x<<endl;
return 0 ;
}
This code seems to be correct but is not. Here 'i' is returned as a reference to fun() and 'i' is local to this function. So when the function fun() is finished, it will deleted 'i' from its stack. Means 'i' is no longer available and 'x' is pointing to 'i'. In this case, 'x' has no idea that 'i' is no longer available. Hence it is a dangling reference.