473,587 Members | 2,579 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

return reference to local variable ?

Hello,

This make me very confusing:

----------------------------------
int &kkk() {
int a = 5;
return a;
}

int main() {
int b = kkk();
}
----------------------------------

"b" should be undefined as many articles say. However, I have tested
in g++ and Visual C++, the result of b is 5 !?

I guess g++ and Visual C++ choose to implement the "undefined" state
in this case as trying to get the value of the reference to local
variable thereby making "b" has the expected result

I'm I wrong ?
Jul 22 '05 #1
6 6072
* romerun:
Hello,

This make me very confusing:

----------------------------------
int &kkk() {
int a = 5;
return a;
}

int main() {
int b = kkk();
}
----------------------------------

"b" should be undefined as many articles say. However, I have tested
in g++ and Visual C++, the result of b is 5 !?

I guess g++ and Visual C++ choose to implement the "undefined" state
in this case as trying to get the value of the reference to local
variable thereby making "b" has the expected result

I'm I wrong ?


Yes.

It's simply that nothing has yet corrupted the memory area that the local
variable occupied, at the point where the value is used.

There is no guarantee for that and it might turn out differently with
different compiler options (not to mention different compilers).

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 22 '05 #2
romerun wrote:

Hello,

This make me very confusing:

----------------------------------
int &kkk() {
int a = 5;
return a;
}

int main() {
int b = kkk();
}
----------------------------------

"b" should be undefined as many articles say. However, I have tested
in g++ and Visual C++, the result of b is 5 !?

I guess g++ and Visual C++ choose to implement the "undefined" state
in this case as trying to get the value of the reference to local
variable thereby making "b" has the expected result

I'm I wrong ?


Yep.
The above works just per coincidence.
In this particular program the memory state of the
program hasn't changed enough and thus you get the
result you expect. But as said: This is just a
coincidence in this special case. It is *not*
because the compiler writers tryed to help
you in some clever way.

When a variable goes out of scope, we say the variable
is destroyed. Well. That's what we say. But in a computer
acutally nothing is physically destroyed. The variable
was assigned a memory location and that memory location
holds the value. So when a variable gets destroyed, its
corresponding memory location is marked as beeing free
but that's it. The memory location still holds the value,
until the program uses it for something else.

--
Karl Heinz Buchegger
kb******@gascad .at
Jul 22 '05 #3
romerun wrote:
int &kkk() { int a = 5; return a; }
int main() { int b = kkk(); }

"b" should be undefined as many articles say. However, I have tested
in g++ and Visual C++, the result of b is 5 !?


In this particular case it's 5 only because that particular location has
been freed but not yet reused. Not only is this specific to this
program, compiler, and set of compiler options, but if you hold onto the
reference which is returned, insert a call to another function, and then
check the value of b, you'll see how fragile this behaviour can be:

#include <iostream>
int &kkk() { int a = 5; return a; }
void jjj() { int d = 10; }
int main() {
int& b = kkk();
jjj();
std::cout << b;
}

Although the output of this program is undefined, on your platform with
optimizations off it's likely to output 10.
--
Derrick Coetzee
I grant this newsgroup posting into the public domain. I disclaim all
express or implied warranty and all liability. I am not a professional.
Jul 22 '05 #4
Karl Heinz Buchegger <kb******@gasca d.at> wrote in message news:<41******* ********@gascad .at>...
romerun wrote:

Hello,

This make me very confusing:

----------------------------------
int &kkk() {
int a = 5;
return a;
}

int main() {
int b = kkk();
}
----------------------------------

"b" should be undefined as many articles say. However, I have tested
in g++ and Visual C++, the result of b is 5 !?

I guess g++ and Visual C++ choose to implement the "undefined" state
in this case as trying to get the value of the reference to local
variable thereby making "b" has the expected result

I'm I wrong ?


Yep.
The above works just per coincidence.
In this particular program the memory state of the
program hasn't changed enough and thus you get the
result you expect. But as said: This is just a
coincidence in this special case. It is *not*
because the compiler writers tryed to help
you in some clever way.

When a variable goes out of scope, we say the variable
is destroyed. Well. That's what we say. But in a computer
acutally nothing is physically destroyed. The variable
was assigned a memory location and that memory location
holds the value. So when a variable gets destroyed, its
corresponding memory location is marked as beeing free
but that's it. The memory location still holds the value,
until the program uses it for something else.


Do you have cases of "return ref to local var" that doesn't work (in g++ or vc++) ?
Jul 22 '05 #5
romerun wrote:
Karl Heinz Buchegger <kb******@gasca d.at> wrote in message news:<41******* ********@gascad .at>...
romerun wrote:
Hello,

This make me very confusing:

----------------------------------
int &kkk() {
int a = 5;
return a;
}

int main() {
int b = kkk();
}
----------------------------------

"b" should be undefined as many articles say. However, I have tested
in g++ and Visual C++, the result of b is 5 !?

I guess g++ and Visual C++ choose to implement the "undefined" state
in this case as trying to get the value of the reference to local
variable thereby making "b" has the expected result

I'm I wrong ?


Yep.
The above works just per coincidence.
In this particular program the memory state of the
program hasn't changed enough and thus you get the
result you expect. But as said: This is just a
coincidence in this special case. It is *not*
because the compiler writers tryed to help
you in some clever way.

When a variable goes out of scope, we say the variable
is destroyed. Well. That's what we say. But in a computer
acutally nothing is physically destroyed. The variable
was assigned a memory location and that memory location
holds the value. So when a variable gets destroyed, its
correspondi ng memory location is marked as beeing free
but that's it. The memory location still holds the value,
until the program uses it for something else.

Do you have cases of "return ref to local var" that doesn't work (in g++ or vc++) ?


If you tried this in an environment that allowed multiple threads of
execution, it is guaranteed to fail. Usually at a bad time.

-Rich
--
Richard Pennington
Email: ri**@pennware.c om
http://www.pennware.com ftp://ftp.pennware.com
Jul 22 '05 #6
* romerun:

Do you have cases of "return ref to local var" that doesn't work (in g++ or vc++) ?


To corrupt the memory formerly occupied by the variable, simply evaluate
an (suitable) expression involving variables that cannot be optimized
away, or pass the reference to a function that has its own locals.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 22 '05 #7

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

Similar topics

2
2683
by: Kench | last post by:
I was curious and playing with pointers and references to see what's different between them. Other than the obvious ones involving C++ syntax & things like references cannot be modified with addition & subtraction, pointers can be modified, both are similar. It stated me going what are the diferrence between a reference vairable and local...
25
4129
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) {...
14
2015
by: Gama Franco | last post by:
Hi, I'm designing an interface for a shared library, and I would like to know if there is a standard about how to return an object to the user. I will use exceptions to report errors, so there are at least four ways to do it. For example if we have a method named M, that receives a reference to parameter p and returns object o.
5
3034
by: Neal Coombes | last post by:
Posted to comp.lang.c++.moderated with little response. Hoping for better from the unmoderated groups: -------- Original Message -------- Subject: Return appropriately by value, (smart) pointer, or reference Date: 27 Aug 2005 15:13:23 -0400 From: Neal Coombes <nealc@trdlnk.com> Organization: Aioe.org NNTP Server To: (Usenet) Newsgroups:...
2
2085
by: Jess | last post by:
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.
4
2279
by: | last post by:
The output is: 1234 After getline: 1234 After renew: 1234 After retnp: İİİİİİİİİİİİİİİİG After getp: İİİİİİİİİİİİİİİİG -----What happen after renew/retnp call?------- Why not return a true array? -----The code is as followed------------------- #include <iostream.h>
7
3977
by: George2 | last post by:
Hello everyone, I am reading some code from other people, there are some code like this, class Foo { };
68
4586
by: Jim Langston | last post by:
I remember there was a thread a while back that was talking about using the return value of a function as a reference where I had thought the reference would become invalidated because it was a temporary but it was stated that it would not. This has come up in an irc channel but I can not find the original thread, nor can I get any code to...
2
1832
by: zheng4t | last post by:
I am learning C++. I found the following code in the book The C++ Programming Language by Bjarne Stroustrup. struct Pair { string name; double val; }; vector<Pairpairs; double& value(const string& s)
0
7918
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...
0
7843
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...
0
8206
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8340
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...
1
7967
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
5392
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...
0
3840
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3875
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2353
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.