Function returning reference --help

Hi, I'm very confused about how function returns refenrence:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;
double & GetWeeklyHours()
{
    double h = 46.50;
    double &hours = h;
    return hours; //return reference to local variable ????

}
int main() {
	double a = GetWeeklyHours();
	cout << a << endl; //ref to local variable did not get out of scope lol??
	return 0;
}

it realy return 46,5 ?!
can someone explain me that behvior please.
Your code is bad. 'h' does in fact go out of scope and therefore GetWeeklyHours returns garbage.

Whether or not the garbage you're getting back is 46.5 is unreliable and unpredictable. You might get 46.5 or you might get -2394293. There's no way to know.

Really, there is no reason to return a reference here. Just return a normal double.
tnx for your reply,
howerver I dont understand what does returning by reference mean then?
how returning by reference work and when sould I return by reference?
obviously the code bellow has no sence:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;
double & GetWeeklyHours(double& x) {
    return x;
}

int main() {
	double s = 2;
	double a = GetWeeklyHours(s);
	cout << a << endl;
	system("pause");
	return 0;
}


can someone share some simple example :)
@codekiddy

Your 1st example is OK, because before h or &hours go out of scope a receives a copy of it's value (46.5).
No error, just pointless.

Edit:

If you had written
 
    double a& = GetWeeklyHours();

it would have been an error (or undefined behaviour, I'm not sure).
Last edited on
Your 1st example is OK


No, his first example is wrong. The reference is dereferenced in main, at which point the variable it refers to is no longer in scope, therefore it's a bad dereference and is undefined behavior.


howerver I dont understand what does returning by reference mean then?


It's typically only done for container classes to return an element within the container. For example, vector's [] operator returns a reference.

Returning a reference allows the returned value to be "assigned". But note that the value you return MUST have a scope larger than the function. Typically it's a member of the class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Example
{
private:
  int myarray[10];

public:
  // overload the [] operator to return a reference:
  int& operator [] (int index)
  {
    return myarray[index];  // return the appropriate element of 'myarray'
    //  this is OK because myarray will still be in scope after this function exits
  }
};


int main()
{
  Example e;  // our example object

  e[5] = 10; // this is like saying e.myarray[5] = 10

  cout << e[5];  // prints 10
}
Last edited on
I beg to differ.
The reference gets copied before it goes out of scope.
Only if codekiddie's a were a reference it would be wrong.

Otherwise
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

double GetWeeklyHours()
{
	double h =46.5;
	return h;
}

int main ()
{

  double a = GetWeeklyHours();
  std::cout << a << '\n';
  
  return 0;
}

would be wrong too, because h goes out of scope too.

Important is whether a is a reference or not.

Edit: typo
Last edited on
thankyou for clarification Dish..
so function returning a refrence must always return ref to object which does not go out of scope.

I've copy my example from http://www.functionx.com/cpp/examples/returnreference.htm
it look's that guy who wrote this has no clue about C++

one more question:

1
2
3
4
5
//FUNCTION
double & GetWeeklyHours(double& x) {
    //do something with x
    return x;
}


now this function has sense...
I mean it's OK to use ref returning function in such way, isn'it?
Last edited on
would be wrong too, because h goes out of scope too.

Yeah, it goes out of scope, but after it has been copied to the return value.

When returning a reference, h goes out of scope before the copy in main() is made.
I mean it's OK to use ref returning function in such way, isn'it?

Yeah, it's allowed...

now this function has sense...

...but I'm not so sure about this part. It is a strange and unusual thing to do (that is, passing out a reference that was passed in).
Last edited on
If I'm really wrong about this, shouldn't my compiler (MSVC10) give me a warning(-Wall) when I do this (with a being a normal variable)?
Because it does not. Even when I make a a reference. *scratching my head*
It diligently warns me when I try this with a pointer(as expected).
@Caligulaminus

I thnk it returns a value of 46.5 (and not an error) because the address at which was stored that value has not been jet modified. (it's still of size double with value stored) and reference is thus correct, otherwise it will return some unpredictable value and access violation.

that means if the value vas not modified yet it could be in few seconds or minutes as program goes furter...

lol I'm geting the point now.

...but I'm not so sure about this part. It is a strange and unusual thing to do (that is, passing out a reference that was passed in).

well it can be usefull maybe to assign the value to some another variable, and then call function back to restore previous value of the reference.
thus you'll have 2 variables : modified and original (for some testig or whatever).
@codekiddy
I thnk it returns a value of 46.5 (and not an error) because the address at which was stored that value has not been jet modified. (it's still of size double with value stored) and reference is thus correct, otherwise it will return some unpredictable value and access violation.

that means if the value vas not modified yet it could be in few seconds or minutes as program goes furter...


I'm fully aware of those mechanisms. Just the same as if we used a pointer here.
If you and Athar are right (which I'm gladly willing to admit) I'm wondering, why my compiler does not warn me as it does with pointers to local variables.
In essence the situation is not very much different...

Maybe somone can ask his gcc (or other) for it's opinion/reaction?
well it can be usefull maybe to assign the value to some another variable, and then call function back to restore previous value of the reference.
thus you'll have 2 variables : modified and original (for some testig or whatever).

Not exactly sure what you mean. Why do you have to return a reference or why are you passing by reference in the first place? But in any case, while I'm sure there's some practical use for it, it's still uncommon.

shouldn't my compiler (MSVC10) give me a warning(-Wall) when I do this (with a being a normal variable)?

It probably should. gcc emits a warning in such cases.
Thanks Athar.
maybe because when pointer goes out of scope it becomes a dangling pointer which compiler see.

the same porblem I had is with char*
1
2
char* a = "test";
a[2] = 'c';

compiler will not warn you but program will not run correctly...

to avoid this you have to use const...
1
2
const char* = "test"
a[2] = 'c';

now compiler warns!!
tnx to everyone so far...
I'm marking this thread solved.
Topic archived. No new replies allowed.