Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

pass variable by its address (pointers)

just programming features

pass variable by its address (pointers)

by  baad  Posted    (Edited  )
hie guyz
this faq is for those people who would want something like the following:
I would like to pass a variable from one function to another function, change this variable in the second function and when returned to the first function the value would have been changed here.


well, IMHO the only objects that pass by value - local variables (correct me if i'm wrong)
you can pass a variable like a pointer (pass an address) through special functions:

1) write

function scall(func)
//call "special" function
{
var sf=func;
for(var ii=1;ii<scall.arguments.length;ii++) {
rg=new RegExp("argv\\["+ii+"\\]","g");
sf=sf.replace(rg,scall.arguments[ii]);
}
return sf;}

2) define "special" function itself:

var FUN="argv[1]++;argv[2]+=argv[1];"



you c, that it is not a function, but a string, arguments written just like in C's main()

3)checkin it:

function test(){
var A=10;
var B=20;
//arguments passed like strings
eval(scall(FUN,"A","B"));
alert("A="+A+" B="+B);
}

looks like it works.. but why bothering so much?

you could (& i think it is the best way 2 do it) make objects from your variables
function Int(x){
this.v=x;
}

function inc(p){
p.v++;
}

function test(){
var A=new Int(10);
inc(A);
alert(A.v);
}


feel free 2 tell me if something is wrong, looks like it works..
wuoah.. :)
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top