Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope of variables in a delegate

I found the following rather strange. Then again, I have mostly used closures in dynamic languages which shouldn't be suspectable to the same "bug". The following makes the compiler unhappy:

VoidFunction t = delegate { int i = 0; };

int i = 1;

It says:

A local variable named 'i' cannot be declared in this scope because it would give a different meaning to 'i', which is already used in a 'child' scope to denote something else

So this basically means that variables declared inside a delegate will have the scope of the function declared in. Not exactly what I would have expected. I havn't even tried to call the function. At least Common Lisp has a feature where you say that a variable should have a dynamic name, if you really want it to be local. This is particularly important when creating macros that do not leak, but something like that would be helpful here as well.

So I'm wondering what other people do to work around this issue?

To clarify I'm looking for a solution where the variables I declare in the delegete doesn't interfere with variables declared after the delegate. And I want to still be able to capture variables declared before the delegate.

like image 969
Anders Rune Jensen Avatar asked Jan 01 '09 12:01

Anders Rune Jensen


People also ask

What are the scopes of variables?

In simple terms, scope of a variable is its lifetime in the program. This means that the scope of a variable is the block of code in the entire program where the variable is declared, used, and can be modified.

What is variable scope example?

Variables have a global or local "scope". For example, variables declared within either the setup() or draw() functions may be only used in these functions. Global variables, variables declared outside of setup() and draw(), may be used anywhere within the program.

What is the scope of a variable declaration?

A scope is a region of the program and broadly speaking there are three places, where variables can be declared: Inside a function or a block which is called local variables, In the definition of function parameters which is called formal parameters. Outside of all functions which is called global variables.


1 Answers

It has to be that way to allow anonymous methods (and lambdas) to use local variables and parameters scoped in the containing method.

The workarounds are to either use different names for the variable, or create an ordinary method.

like image 189
Arjan Einbu Avatar answered Nov 08 '22 13:11

Arjan Einbu