in reply to Reference to a function

I think what the author was trying to show was that with C your pointers are real pointers to memory and once a variable is set up in a function its memory is fixed. If you fiddle with a pointer to it you will change it. Here is an example:
int *mysub (); main() { int* x; x = mysub(); printf("in main x = %d\n", *x); *x = 5; x = mysub(); } int *mysub () { int z; printf("in sub z = %d\n", z); z = 3; return &z; }
Compiling gives a warning but it still compiles.
$ make temp gcc temp.c -o temp temp.c: In function `mysub': temp.c:13: warning: function returns address of local variable
running it gives you:
$ temp in sub z = 0 in main x = 3 in sub z = 5
as you can see main "reached into" mysub and changed z. There is no equivalent way to "reach into" a perl function and fiddle with its my variables
use strict; my $x; $x = &mysub; printf "in main \$x = %d\n", $$x; $$x = 5; $x = &mysub; sub mysub () { my $z; printf "in sub \$z = %d\n", $z; $z = 3; return \$z; }
outputs:
$ perl temp.pl in sub $z = 0 in main $x = 3 in sub $z = 0
as you can see the main program could not "reach in" and change the value of $z in mysub even though you dereferenced the reference it returned. The my $z in mysub creates a new variable every time and does not just reference a fixed memory location as in C.

Before an expert points it out:

I know, I know, the memory locations may change in C depending on hardware, OS, etc. but I am trying just to give and example of things that are possible in C, not necessarily good programming practice.

Update -- I noticed that if you make z static in mysub

int *mysub () { static int z; ...
the compiler (gcc in my case) will not emit a warning but the output of the program is the same.

--

flounder