Aliaspooryorik
ColdFusion ORM Book

By value and by ref with nested data types

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:

byref byval nested

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!


3 comments

  1. I am not so sure about the conclusion you are making about deep-copy of arrays. If you look at your changeArray() method, it only touches the array itself:

    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
  2. Ack - you're right! Thanks Ben - I'm updating the post right now :)

    Comment by John Whish – January 29, 2010
  3. No worries my man - it's all about team work :)

    Comment by Ben Nadel – January 29, 2010

Leave a comment

If you found this post useful, interesting or just plain wrong, let me know - I like feedback :)

Please note: If you haven't commented before, then your comments will be moderated before they are displayed.

Please subscribe me to any further comments
 

Search

Wish List

Found something helpful & want to say ’thanks‘? Then visit my Amazon Wish List :)

Categories

Recent Posts