Compiling gives a warning but it still compiles.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; }
running it gives you:$ make temp gcc temp.c -o temp temp.c: In function `mysub': temp.c:13: warning: function returns address of local variable
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$ temp in sub z = 0 in main x = 3 in sub z = 5
outputs: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; }
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.$ perl temp.pl in sub $z = 0 in main $x = 3 in sub $z = 0
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
the compiler (gcc in my case) will not emit a warning but the output of the program is the same.int *mysub () { static int z; ...
--
flounder
In reply to Re: Reference to a function
by flounder99
in thread Reference to a function
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |