I...wondered if you could tell me if you think this is correct?
It's crap. Period. Full stop.
Use of the returned value will result in undefined behavior.
From the C++ language standard ISO/IEC 14882
In section 3.7, line 4
The lifetime of a reference is its storage duration
In section 3.7.2, line 1
Local objects ... not explicitly declared
extern have automatic storage duration. The storage of these objects lasts until the block in which they are created exits.
In section 1.3.2 the definition of undefined behavior is given as
behavior, such as might arise upon use of an erroneous program construct or erroneous data, for which this International Standard imposes no requirements.
Here's the thing: Use of the returned value of the example function may give the value that the programmer expected. It may give junk. Showing that it "works" in a specific program for a particular function compiled by a particular version of a particular compiler doesn't make it OK. Undefined is undefined.
Note that if you test something and it seems to "work," that doesn't mean that the code is correct. Because of the ever-present possibility of undefined behavior, you can not, in general, prove a program is correct by testing alone. I mean, you should test, test, and test some more, but you still gotta write correct code.
Bottom line: Reuse of storage beyond its lifetime is undefined behavior. Compilers are not required to give warning or error messages for this specific type of undefined behavior.
Good point about ISRs gardner, I'll change my code to
x = GetWeeklyHours();
I respectfully recommend that you make maximum attempts to write code that does not ever result in undefined behavior. Disabling interrupts does not make the behavior defined.
I think it does work,,,, because it's a 'value type'
It is undefined behavior. It is not a "value type." It is a reference. If a function returns a reference to a local variable, the result is worthless.
But that will probably work because what really happens is a value copy.
No, there is no copy involved. The function returns a reference, not a copy of anything. If it seems to "work" by displaying the wrongfully-expected value, well, that's too bad, since the programmer might assume that the code is correct. The code is crap. (But I said that already.)