By value and by ref with nested data types
January 29, 2010
Andy posted a comment on my previous post Passing values by reference or value, where he asked what happens if you have an array (which is passed by value), inside a struct (which is passed by ref). Well, the short answer is that the containing variable type determines the behaviour. I thought the easiest way to explain is to post some sample code and output, so here it is:
<cfscript>
WriteOutput( "<p>Arrays are passed by value</p>" );
// nest structs inside and array
myarray = [ {name="John"}, {name="Aliaspooryorik"} ];
WriteDump( myarray );
changeArray( myarray );
WriteDump( myarray );
WriteOutput( "<p>Structs are passed by ref</p>" );
// nest an array inside a struct
mystruct = { name=['John','Aliaspooryorik'] };
WriteDump( mystruct );
changeStruct( mystruct );
WriteDump( mystruct );
function changeArray( value )
{
arguments.value[ 1 ].name = "Fred";
}
function changeStruct( value )
{
arguments.value.name = "Aliaspooryorik";
}
</cfscript>
The output you get when you run the code is:

As you can see, the array is passed by value, but the struct inside it still passed as a reference (or pointer to the place it is stored in memory), so when it is manipulated inside a function call, then the original is also effected.
Edit: Quick thanks to Ben Nadel, for pointing out a error in my original post!
- Posted in:
- ColdFusion
3 comments
Leave a comment
If you found this post useful, interesting or just plain wrong, let me know - I like feedback :)





function changeArray( value ){
arguments.value[ 1 ] = "Aliaspooryorik";
}
Since the array itself is passed by value, this change doesn't take place.
However, if you changed the struct contained WITHIN the array, I think you'd see that change persisted (since the the struct pointers remain intact):
function changeArray( value ){
arguments.value[ 1 ].Name = "Aliaspooryorik";
}
Comment by Ben Nadel – January 29, 2010
Comment by John Whish – January 29, 2010
Comment by Ben Nadel – January 29, 2010