In languages ​​that create a new scope every time in a loop block, does every new local variable of a local variable get created each time in that new scope?

It seems that in C, Java and Ruby (as opposed to Javascript) a new scope is created for each iteration of the loop block, and the local variable defined for the loop actually turns into a local variable each time and is written in that new scope?

For example, in Ruby:

p RUBY_VERSION

$foo = []

(1..5).each do |i|
  $foo[i] = lambda { p i }
end

(1..5).each do |j|
  $foo[j].call()
end

      

printout:

[MacBook01:~] $ ruby scope.rb
"1.8.6"
1
2
3
4
5
[MacBook01:~] $ 

      

So it looks like when a new scope is created, a new new local copy is i

also created and written to this new scope, so when the function is executed later, the "i" is found in these visibility chains as 1, 2, 3, 4, 5 respectively. It's true? (This sounds like a heavy operation).

Contrast this with

p RUBY_VERSION

$foo = []

i = 0

(1..5).each do |i|
  $foo[i] = lambda { p i }
end

(1..5).each do |j|
  $foo[j].call()
end

      

This time the parameter is i

set before entering the loop, so Ruby 1.8.6 does not put this i

in the new scope created for the loop, and so when i

viewed into the scope chain, it always refers to the i

one that was in the outer scope, and each time gives 5:

[MacBook01:~] $ ruby scope2.rb
"1.8.6"
5
5
5
5
5
[MacBook01:~] $ 

      

I heard that in Ruby 1.9 i

will it be treated as local defined for a loop even if there is i

one defined earlier?

The operation of creating a new scope, creating a new local copy i

every time through the loop, seems cumbersome, as it doesn't seem to matter unless we refer to functions at a later time. So, when the functions don't need to be called later, can the C / Java interpreter and compiler try to optimize it so there isn't a local copy i

every time?

+2


a source to share


1 answer


This is similar to the topic discussed here: http://math.andrej.com/2009/04/09/pythons-lambda-is-broken/ . In some programming languages, when you iterate over a variable, the body of the loop construct is bound to a single variable that is incremented. In other cases, a new loop variable is created per loop iteration.



As for the lexical scope, note that the JavaScript functions are the only structures that form the region (the braces for if

, while

, for

etc.). In C / C ++, any pair of curly braces forms a scope.

+1


a source







All Articles