0

Code 1:

#include<iostream>
using namespace std;

int& func()
{
	int a=6;
	return a;
}

int main(void)
{
	int a = func();
	cout<<a;
     
      cin.get();
      return 0;
}

According to my thought , first of all func() will create a temporary reference to a (as it is returning by reference) , and then through that temporary reference it will provide value to a.

Please correct me if I'm wrong!


Code 2:

#include<iostream>
using namespace std;

int& func()
{
	int a=6;
	return a;
}

int main(void)
{
	int& a = func();
	cout<<a;
     
      cin.get();
      return 0;
}

I think this time too func will create a temporary and assign value to a as a reference.But after function is returned shouldn't func value be trashed ?
How 'a' in main is still printing correct values ?

Please somebody explain.

Regards!

2
Contributors
3
Replies
4
Views
6 Years
Discussion Span
Last Post by arkoenig
0

Both of your examples are wrong: A function must never return a reference to a local variable. Whatever output such a program produces is the result of coincidence and cannot be trusted.

0

Please threw some light how actually this coincidence does happen ?

0

The usual way is that the variable's memory has been deallocated but the program hasn't gotten around to putting anything new in that particular piece of memory yet. So by luck it still has the last value you gave it.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.