Physician
Physician

Reputation: 483

Variables more local than the rest of local variables ( is it really "more local" or just "isolated" from the rest that are "as local as" it's?)

I've got a quite small and straight forward question, I'll would like to get a sure answer for, and thank you guys in advance:

Inside a method ( say the main for instance ), I can add curly braces {} for any section of the code to scope some lines as locals.

Here's my example:

public static void Main (string[] args)
{
int a = 1;

{ int b = 2;
Console.WriteLine(b); 
}

Console.WriteLine(a);


}

The variable "int b" is obviously non-accessible in the out side of the curly braces, now my question is about this variable's memory position, is it going to be in the same stack frame with the main method in the same stack of memory, or it's going to be held in yet a newer stack frame on top of the main method's stack (like called method's parameters and local variables inside another method)?

Upvotes: 0

Views: 100

Answers (2)

Nikita Shrivastava
Nikita Shrivastava

Reputation: 3018

No, braces do not act as a stack frame.b is also an automatic variable for main method & will be treated same as a but with additional scoping So,it going to be in the same stack frame with the main method in the same stack of memory.

Upvotes: 3

CodingFeles
CodingFeles

Reputation: 384

I think it would be useful to differentiate lifetime and scope:

Lifetime and scope are often confused because of the strong connection between the lifetime and scope of a local variable. The most succinct way to put it is that the contents of a local variable are guaranteed to be alive at least as long as the current "point of execution" is inside the scope of the local variable. "At least as long" of course implies "or longer"; capturing a local variable, for example, extends its lifetime

Take a look at source

Also, according to this answer and comment to it:

It is very much an implementation detail of the JIT compiler.

C# code is translated to IL code and

IL works with an operation stack, but this does not directly correspond to a 'call stack'

It looks like it's implementation-dependent.

Upvotes: 2

Related Questions