473,671 Members | 2,154 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

return type of a function that returns a local variable

Hello,

I understand that if a function "f" has a local variable "a", and
after it returns, "a" vanishes. If "f" returns "a" as a result, then I
noticed the following:

1. if the return type is "a&", then compiler complains reference to
the local variable "a".
2. if the return type is "a", then everything works fine.

I think this is because in the first case, the return is copy-by-
reference, and we can't reference a local var. In the second case, it
is a copy-by-value, and it's correct because we can copy the value
from a local var, is this right?

Thanks!

Mar 22 '07 #1
2 2090
On 22 Mar, 12:11, "Jess" <w...@hotmail.c omwrote:
Hello,

I understand that if a function "f" has a local variable "a", and
after it returns, "a" vanishes. If "f" returns "a" as a result, then I
noticed the following:

1. if the return type is "a&", then compiler complains reference to
the local variable "a".
2. if the return type is "a", then everything works fine.
Your description is a bit confused. In your first paragraph a is an
object, in your second a is a type. But I think I understand what you
mean.
I think this is because in the first case, the return is copy-by-
reference, and we can't reference a local var. In the second case, it
is a copy-by-value, and it's correct because we can copy the value
from a local var, is this right?
Yes.

// foo1 is bad. Don't do this.
int& foo1()
{
int i = 42;
return i;
}

// foo2 is OK.
int foo2()
{
int j = 0;
return j;
}

int main()
{
int& int_reference = foo1();
int int_value = foo2();
}

In the code above, in the function main, int_reference is initialised
as a *reference to* the int i inside function foo1. As you correctly
suspect, after foo1 returns i no longer exists and so int_reference
refers to nothing. It is a dangling reference. Any use of
int_reference has undefined behaviour.

int_value on the other hand is initialised with *a copy* of the int j
from inside function foo2. It doesn't matter that j no longer exists
after foo2 returns because the copy of j was taken while j did still
exist.

Gavin Deane

Mar 22 '07 #2
Thanks, that solves my problem! :)

Mar 22 '07 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

25
4137
by: cppaddict | last post by:
I'd like to know what goes on under the hood when methods return objects. Eg, I have a simple Point class with two members _x and _y. It's constructor, copy constructor, assignment operator and additon operator (which returns another Point object, and which my question is about) are as follows: Point::Point(int x, int y) : _x(x), _y(y) { }
8
13997
by: Ravindranath Gummadidala | last post by:
Hi All: I am trying to understand the C function call mechanism. Please bear with me as I state what I know: "every invocation of a function causes a frame for that function to be pushed on stack. this contains the arguments this function was called with, address to return to after return from this function (the location in the previous stack frame), location of previous frame on stack (base or start of this frame) and local variables...
23
3587
by: Nascimento | last post by:
Hello, How to I do to return a string as a result of a function. I wrote the following function: char prt_tralha(int num) { int i; char tralha;
11
2762
by: randomtalk | last post by:
hi, i have the following recursive function (simplified to demonstrate the problem): >>> def reTest(bool): .... result = .... if not bool: .... reTest(True) .... else: .... print "YAHHH" .... result =
7
5820
by: ashu | last post by:
look at code #include<stdio.h> int *mult(void); int main(void) { int *ptr,i; ptr=mult; for(i=0;i<6;i++) { printf("%d",*(ptr++));
14
1936
by: Alexander Stoyakin | last post by:
Hello! Please advise on the following issue. I have a function which returns 1 or 0 in multiple branches, and it must perform the same code before each return, like this: int fun() { if (some code) { restore(param1,param2,param3,param4,param5); return 1;
18
2087
by: terminator(jam) | last post by:
consider: struct memory_pig{//a really large type: memory_pig(){ std::cout<<"mem pig default\n"; //etc... }; memory_pig(memory_pig const&){
13
13183
by: hari | last post by:
Hi all, Is it legal to return a local variable from function. Regards Hari
7
2784
by: asit | last post by:
#include <stdio.h> //#include <stdlib.h> int main() { int c; printf("c before call=%d\n",c); c=message(); printf("c after call=%d\n",c); return 0;
0
8476
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8393
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8820
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8670
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7433
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6223
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5695
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4406
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2810
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.