What is the difference between two codes?

Dear all,

Here are two kinds of codes, In the first one, I use global ,and the other one not use global, What is the difference between them?

julia> i = 1
1

julia> while i < 5
           println(i)
           global i += 1
       end
julia> i = 1;

julia> while i < 5
           println(i)
           i += 1
       end;
1
2
3
4

https://docs.julialang.org/en/v1/manual/variables-and-scoping/

1 Like

It seems that we need not use global in the function. So in my example, two kinds of codes are the same.

1 Like

See: Scope of loops · JuliaNotes.jl

All of your code in the REPL is already running in the global scope, so there is no difference.

Compare it to this

julia> i = -1;

julia> begin 
         local i = 1
         while i < 5
            print(i, " ") # save some vertical space
            i += 1
         end 
       end
1 2 3 4
julia> i
-1

Something to keep in mind: while is a “soft” scope. “Soft” just means its scoping rules on accessing global variables is different in interactive contexts (REPL, notebooks) versus non-interactive ones (.jl scripts, eval-ed expressions).
You can check script behavior really quick this way:

@eval begin
  # paste code
end