Significance of global keyword

Can someone make me understand the actual significance of global keyword in Julia?

2 Likes

Presumably you’ve read the manual: Scope of Variables · The Julia Language?

If so, maybe you can be a bit more specific, what your question is.

3 Likes

Thank you @mauro3, I was confused when we declare a variable outside ,not within any block, what is its scope?

Here it says Scope of Variables · The Julia Language
“Each module introduces a new global scope, separate from the global scope of all other modules—there is no all-encompassing global scope.”

4 Likes

It is global scope, it is the only possibility and you do not need to use the keyword global there. You use global when you want to refer to a global variable inside a block, specially if the block start assigning a value to the global variable (e.g., function f(...); global x = 1; ...; end). Without the global it is indistinguishable from just creating a local variable of the same name (i.e., function f(...); x = 1; ...; end).

Complementing what @mauro3 said, you could ask yourself, but what if I am in the REPL outside of any module?, well, then you are inside the implicit module called Main, and every variable you define in the REPL are global variables of this implicit module.

7 Likes

Thanks @Henrique_Becker and @mauro3 , for clearing my queries. Now I have greater understanding of the topic.

3 Likes