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!

Recommended Answers

All 3 Replies

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.

Please threw some light how actually this coincidence does happen ?

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.