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