سؤال

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.

هل كانت مفيدة؟

المحلول

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top