Prevent overriding an array

Hi,

if I perform the following code

function next_step(x, i)
    x[i] = x[i]+1
    return x
end

x = [0,0,0,0]
x_a = next_step(x, 1)

the value of x is [1,0,0,0]. The value should be still [0,0,0,0].

Why do the value of x change? And how to avoid it?

Try

function next_step(x, i)
    y = copy(x)
    y[i] = y[i]+1
    return y
end

I would strongly suggest having a look into the manual.

4 Likes

Julia using a passing model called “pass by sharing”. This is the same behavior you would see from python, Java, and most other programming languages.

2 Likes