Guray scribbled the following:
> Hi,
> please consider the code:
> int myFunction(void)
> { int x=0;
> return x;
> }
> Now, my friend claimed that the code above is erroneous
> because the int variable x is created in the stack. The function
> returns the address of x in the stack. But the addresses in the
> stack may change outside the function myFunction.
Your friend is talking out of his tailpipe. He's just plain wrong.
The function doesn't return the address of *ANYTHING AT ALL*. It
returns the *VALUE* of x, which is a separate concept from x itself.
Your function is completely OK, legal, valid, kosher, all-singing,
all-dancing and hunky dory.
> I found his argument quite plausible. However, I have seen
> so many functions like the one above. I have written functions
> doing what myFunction does, and they worked without error
> for long time.
His argument would be plausible *IF* you were returning the address
of x. But you aren't, so his argument dissolves like O'Boy cocoa
powder into a glass of cold milk and you win your argument.
*THIS* kind of code would be illegal, because of the reason your
friend gives:
int *myFunction(void) {
int x=0;
return &x;
}
but that's a whole different kettle of fish.
> Can anyone clarify this issue ? TIA..
The issue is that there is no address returning in the function, only
value returning, and returning values of any variables whatsoever is
safe.
--
/-- Joona Palaste () ---------------------------\
| Kingpriest of "The Flying Lemon Tree" G++ FR FW+ M- #108 D+ ADA N+++|
|
http://www.helsinki.fi/~palaste W++ B OP+ |
\----------------------------------------- Finland rules! ------------/
"The large yellow ships hung in the sky in exactly the same way that bricks
don't."
- Douglas Adams