Reputation: 1247
I'm just starting in Julia after a strong background in C++. I'm having an issue with my integer variables being reset to what I initialized them as in the beginning of my program.. even though I changed the variable value inside a function. Can anyone explain why this is?
num = 0
function getNum()
num = 1
end
getNum()
num #this returns 0, not 1
This is a problem because I will need to reference that variable in another function.
Upvotes: 0
Views: 325
Reputation: 4366
num
is in global scope (note that the same behavior applies in e.g. Python)
If necessary, you could modify it by referencing as a global:
function getNum()
global num = 1
end
However, it is worth considering whether there is a more effective way to structure your code. Global variables can be useful in some situations, but they can also make code more difficult to reason about.
Upvotes: 2