Julia function argument by reference

Lindon picture Lindon · Feb 6, 2016 · Viewed 10.5k times · Source

The docs say

In Julia, all arguments to functions are passed by reference.

so I was quite surprised to see a difference in the behaviour of these two functions:

function foo!(r::Array{Int64})                                                                                                                                                                                     
        r=r+1                                                                                                                                                                                                      
end


function foobar!(r::Array{Int64})                                                                                                                                                                                  
        for i=1:length(r)                                                                                                                                                                                          
                r[i]=r[i]+1                                                                                                                                                                                        
        end                                                                                                                                                                                                        
end 

here is the unexpectedly different output:

julia> myarray
2-element Array{Int64,1}:
 0
 0

julia> foo!(myarray);

julia> myarray
2-element Array{Int64,1}:
 0
 0

julia> foobar!(myarray);

julia> myarray
2-element Array{Int64,1}:
 1
 1

if the array is passed by reference, I would have expected foo! to change the zeros to ones.

Answer

Reza Afzalan picture Reza Afzalan · Feb 6, 2016

r=r+1 is an Assignment statement, this means it reallocates r, so it no longer refers to its pair in the parent scope. but r[i]=r[i]+1 Mutates r value, mutation is differ from assignment (a good description here), and after that r still refers to its pair variable in the parent scope.