C++ Programming - References - Discussion

Discussion Forum : References - General Questions (Q.No. 12)
12.
Which of the following statements is correct?
  1. We can return a global variable by reference.
  2. We cannot return a local variable by reference.
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:
23 comments Page 1 of 3.

Divya Nesana K said:   6 years ago
Option C is correct.

We can return a global variable by reference.
If you workout a simple program you will get the answer !

And,
We cannot return a local variable by reference.
If you do so, you will get a warning.. which is a no right?

#include<iostream>
using namespace std;

int& a(){
int b=10;
return b;
}

int main(){
a();
}

bix.cpp [Warning] reference to local variable 'b' returned [-Wreturn-local-addr]

Kunal Waghmare said:   6 years ago
For local variable we get warning. But code run successfully. Global variable can be accessed in anyway.

Rupesh said:   6 years ago
We can return only static variable by reference.

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.

Bhan ka loda said:   7 years ago
Answer is [A].

Well we can return both global and local variables by reference.

Jerry said:   7 years ago
Only A should be correct.

Otherwise they should specify what they mean by "can't", because you can actually return a local variable by reference, it's a potential bug, but you "can" do it you won't get any crash or compilation error by doing it.

And returning a reference to a global variable is totally legal.
(1)

Okan said:   8 years ago
int myGlobal = 1978;
int& returnGlobal()
{
return myGlobal;
}
int &myr = returnGlobal();
cout << "Global reference value=" << myr << endl;

It prints 1978 on the screen.
So returning global reference is possible.

Sai kiran said:   8 years ago
We can return a global variable by reference and also we can return local variable by reference (it is not a language error), the user/ programmer has to take care not to return local variable by reference as it might not be there on the stack when he later uses it.

So, if we simply take what is allowed, at least by the compiler, the answer would be A.

Sergey D said:   8 years ago
Correct answer is C: Both 1 and 2 are correct.

Test must be corrected.

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.


Post your comments here:

Your comments will be displayed after verification.