문제

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