List comprehension can't find an already defined variable

I was dealing with an error and in the end it seems to reduce to array comprehension:

c=0
z = [1,2,3,4]
println([c+=i for i in z])

it throws an error:

ERROR: LoadError: UndefVarError: c not defined in local scope
Suggestion: check for an assignment to a local variable that shadows a global of the same name.
Stacktrace:

Or:

ERROR: UndefVarError: c not defined
Stacktrace:
[1] (::var"#1#2")(i::Int64)
@ Main ./none:0
[2] iterate
@ ./generator.jl:47 [inlined]
[3] collect(itr::Base.Generator{Vector{Int64}, var"#1#2"})
@ Base ./array.jl:834
[4] top-level scope
@ REPL[4]:1= 0

But something like

for i in z
        x+=i
       end

or

if 1==1
           x+=1
       end

Works.

When c+=i occurs, there is no pre-existing local c variable to access, and c=0 made a global variable. Comprehensions make a hard local scope, so it will not use a global variable unless you put an explicit global statement.

if works because it doesn’t make a scope. for works because it’s a soft local scope, so it would use a global variable automatically in the REPL or notebooks. It would instead behave like hard local scopes in plainer source files or Julia expressions, though there’s an extra warning:

julia> begin # REPL context
       c=0
       z = [1,2,3,4]
       for i in z
         println(c+=i)
       end
       end
1
3
6
10

julia> eval(quote # evaluate Julia expression
       c=0
       z = [1,2,3,4]
       for i in z
         println(c+=i)
       end
       end)
┌ Warning: Assignment to `c` in soft scope is ambiguous because a global variable by the same name exists: `c` will be treated as a new local. Disambiguate by using `local c` to suppress this warning or `global c` to assign to the existing global variable.
└ @ REPL[9]:5
ERROR: UndefVarError: `c` not defined in local scope
Suggestion: check for an assignment to a local variable that shadows a global of the same name.