C++ Programming - References - Discussion
Discussion Forum : References - General Questions (Q.No. 12)
12.
Which of the following statements is correct?
- We can return a global variable by reference.
- We cannot return a local variable by reference.
Discussion:
23 comments Page 2 of 3.
Wouter van ooijen said:
1 decade ago
You CAN do both in the sense that it syntactically allowed, but returning a local variable by reference yields a program that has undefined runtime behavior. So the point is what is meant by 'CAN'.
Stuvi said:
7 years ago
The Correct answer is C, both 1 and 2 are correct.
@ALL.
Note that 2 says "We cannot return a local variable by reference. ", which is true we _can't_ return a reference to a local variable.
@ALL.
Note that 2 says "We cannot return a local variable by reference. ", which is true we _can't_ return a reference to a local variable.
Varunrao.rao@gmail.com said:
9 years ago
#include<iostream.h>
int i=9;
int& myfunc()
{
return i;
}
int main() {
int g=myfunc();
cout<<g<<endl;
return 0;
}
Here, we can return global variable by reference.
int i=9;
int& myfunc()
{
return i;
}
int main() {
int g=myfunc();
cout<<g<<endl;
return 0;
}
Here, we can return global variable by reference.
Will said:
8 years ago
It would be nice if s/o with access to modify the answer would correct it, because you can return a reference to a global variable and can not return a reference to a local variable.
Rishi said:
1 decade ago
We can Return a global variable, but not a local as a local variable goes out of scope once a function call is over.
Vinay said:
1 decade ago
We can return the global variable by reference and it is wrongly answered here. The correct option is C.
Kunal Waghmare said:
6 years ago
For local variable we get warning. But code run successfully. Global variable can be accessed in anyway.
Raj said:
1 decade ago
We can not return a global variable by reference.
We can return a local variable by reference.
We can return a local variable by reference.
Abhirav Kumar said:
1 decade ago
@Pravee. Already proved that 2 is correct. Is there someone who knows why 1 is incorrect?
Bhan ka loda said:
7 years ago
Answer is [A].
Well we can return both global and local variables by reference.
Well we can return both global and local variables by reference.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers