Running Tests vs. Debugging gives different results

Normally it’s as I told before: variables assigned inside a loop (such as c = ...) are local for each iteration (and the iterator of for loops is local as well), unless explicitly declared global (or in the REPL since 1.5, if there is a global with the same name). But you are right, in debug mode that rule does not hold. Not only in VS Code, also with Debugger.jl:

(after adding a breakpoint in line 9:)

julia> @run encode("XYZ")
Hit breakpoint:
In encode(str) at /home/meliana/prueba/run-length-encoding.jl:2
  5  
  6  n = length(str);
  7  
  8  for i in 1:n
> 9      if i==1 # setup on the first iteration
 10          c = str[1];
 11          runLength = 1;
 12      elseif  c == str[i]
 13          runLength +=1;

About to run: (==)(1, 1)
1|debug> fr
[1] encode(str) at /home/meliana/prueba/run-length-encoding.jl:2
  | str::String = "XYZ"
  | rle::String = ""
  | n::Int64 = 3
  | ::Tuple{Int64,Int64} = (1, 1)
  | i::Int64 = 1
1|debug> c
Hit breakpoint:
In encode(str) at /home/meliana/prueba/run-length-encoding.jl:2
  5  
  6  n = length(str);
  7  
  8  for i in 1:n
> 9      if i==1 # setup on the first iteration
 10          c = str[1];
 11          runLength = 1;
 12      elseif  c == str[i]
 13          runLength +=1;

About to run: (==)(2, 1)
1|debug> fr
[1] encode(str) at /home/meliana/prueba/run-length-encoding.jl:2
  | str::String = "XYZ"
  | rle::String = ""
  | n::Int64 = 3
  | ::Tuple{Int64,Int64} = (2, 2)
  | i::Int64 = 2
  | c::Char = 'X'
  | runLength::Int64 = 1

c exists at the outset of the second iteration, with the value that was assigned in the first one. Bug or feature?

1 Like