The docs say
In Julia, all arguments to functions are passed by reference.
so I was quite surprised to see a difference in the behav
In practice, regardless of theory(call by sharing
), described in previous answer, everything happens in Julia as if pointer variables as arrays were passed by reference
, while scalar variables, such as numbers, were passed by value
.
This is a pain for people like me, used to C or Pascal languages, where one specify in formal parameter part in function declaration, if the parameter is by value
or by reference
.
However, due to Julia's feature that allows return of multiple values in a function, there is an elegant way to simulate parameters by reference
for scalar variables. Obviously this works even for immutable variables like strings, since the variables are recreated.
Julia's Code
function process(a,b,c)
a += c
b *= c
return a*b*c, a, b # normal result, changing "a" and "b"
end
a = 4
b = 7
println("Before: ", a," ",b)
result, a, b = process(a,b,7)
println("After: ", a," ",b," ", result)
Display
Before: 4 7
After: 11 49 3773
a
and b
was both changed inside function process. a
was added to 7 and b
was multiplied by 7