C++ Programming - References - Discussion

Discussion Forum : References - General Questions (Q.No. 2)
2.
Which of the following statements is correct?
  1. Once a reference variable has been defined to refer to a particular variable it can refer to any other variable.
  2. A reference is not a constant pointer.
Only 1 is correct.
Only 2 is correct.
Both 1 and 2 are correct.
Both 1 and 2 are incorrect.
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
16 comments Page 2 of 2.

Anu said:   9 years ago
I think the option 1 is correct.

Pooja said:   8 years ago
A is the correct answer.

Harsha said:   8 years ago
#include<iostream>
using namespace std;
int main()
{
int x = 10;
int& ref = x;
ref = 20;
cout<<ref;
int y=40;
ref=y;
cout<<ref;
return 0;
}

Here reference is referred to another variable 'y' after referring 'x'. How 1st option is correct?

Prashant said:   8 years ago
When we are creating a reference to a variable we are actually giving it a different name so logically now ref and x are the same so whenever you are modifying ref you are modifying x and not changing what is ref referring to so the line.

ref=20 sets x also to 20 and line.
ref=y sets x equal to the value of y,
ref=y does not mean that ref is now a reference to y,
you can try printing x it will give you 40.

Therefore option 1 is incorrect.

Abhijeet said:   6 years ago
#include<iostream>
using namespace std;
int main()
{
int x = 10;
const int const *ptr=&x;
int& ref = x;
ref = 20;
cout<<"before change ref = "<<ref<<endl;
int y=40;
ref=y;
cout<<"after change ref = "<<ref<<endl;
cout<<"but it actually change x and not change only ref i.e.x = "<<x<<endl;
cout<<"add of x= "<<&x<<endl;
cout<<"add of ref = "<<&ref<<endl;
cout<<"add of ptr = "<<&ptr<<endl;
cout<<"ptr = "<<ptr<<endl;


getchar();
return 0;
}

As you can see,

A reference is not a constant pointer.
as pointer has its own address and ref does not.

Vedi G said:   6 years ago
@Anu.

Option 4 is correct because reference cannot have its own address. That's why its is not a constant pointer.

One time it hold one variable address only.


Post your comments here:

Your comments will be displayed after verification.