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 3 of 3.

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

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

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]


Post your comments here:

Your comments will be displayed after verification.