Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does C# bind the local variables up-front? [closed]

Tags:

c#

.net

clr

So in C#, you might have the following code:

void DoSomething()
{
    //some code.
    int x = 5;
    //some more code.
}

As soon as you enter DoSomething, the CLR sets up space for int x. Why does it not wait until it reaches the line with int x =5 on it? Especially since even though x is bound, it doesn't let you actually use it until that line is reached anyway?

like image 399
GWLlosa Avatar asked Feb 02 '12 00:02

GWLlosa


People also ask

Why semicolon is used in C?

The Semicolon tells that the current statement has been terminated and other statements following are new statements. Usage of Semicolon in C will remove ambiguity and confusion while looking at the code. They are not used in between the control flow statements but are used in separating the conditions in looping.

Why do we use hashtag in C?

Application: The ## provides a way to concatenate actual arguments during macro expansion. If a parameter in the replacement text is adjacent to a ##, the parameter is replaced by the actual argument, the ## and surrounding white space are removed, and the result is re-scanned.

What does %D stand for in C?

%d. a decimal integer (assumes base 10) %i. a decimal integer (detects the base automatically) %o.


1 Answers

As soon as you enter DoSomething, the CLR sets up space for int x. Why does it not wait until it reaches the line with int x = 5 on it?

The question is not answerable because the entire question is founded on an incorrect premise. The storage space for the local variable may be:

  • allocated when the method is first entered
  • allocated when control reaches the declaration
  • allocated when control reaches the initialization (assuming initialization and declaration are different)
  • allocated under special circumstances -- if for example the local is a closed-over local of a lambda, or in an iterator block, or in an async block, how and when the local storage is allocated can get complicated
  • elided entirely; if the local is never used then it might not be allocated in the first place.

The C# compiler and the jit compiler definitely ensure that the local storage is allocated in a way that is correct, and attempt to ensure that it is efficient. How they choose to do so depends on the exact situation. It might be more efficient to allocate the space up front, and it might be more efficient to allocate it for only as long as the variable is in use; the jitter is permitted broad lattitude in choosing the lifetime of a local variable. Local variables are permitted to live both longer and shorter than their scopes would imply if the jitter can do so without violating program correctness.

Since the premise of the question is incorrect, there is no answer to the question. Ask a better question.

like image 152
Eric Lippert Avatar answered Oct 05 '22 22:10

Eric Lippert