-3

I'm reading through this wikibook and don't understand what this means within the local variables section? An ELI5 would be helpful <3

faceless
  • 436
  • 1
  • 4
  • 11
  • Constant local variable are public variables that are not inside methods(functions or subroutines). So they are put into a table called "assembly data region". Variables inside methods are put on the execution stack. When a method is called the compiles reserves memory on the execution stack which is the size of the total of all the variables required to execute the method. So if a method declares int a;int b; int c; An integer is 4 bytes so 4 x 3 = 12 bytes are reserved on the stack for the local variables. – jdweng May 16 '17 at 06:08
  • 2
    @jdweng - constant *local* variables *are* declared inside methods. That's what makes them local. – Damien_The_Unbeliever May 16 '17 at 06:09
  • @jdweng - And "variables that are not inside methods" go on the Heap, not in a data region. That's about 'variable' vs 'constant'. – H H May 16 '17 at 06:35

1 Answers1

0

Fun fact - the stack is an implementation detail that is mostly irrelevant. Most references to stack within the C# Spec are to a toy Stack<T> class than references to a/the execution stack.

Let's take a toy method:

public int Compute(int value)
{
   int b = value/2;
   if (b > 10){
      return b + Compute(b);
   }
   return b - 4;
}

This Compute method needs somewhere where it can store the contents of the b variable. Importantly, this method may recurse1, that is, it may call itself, possibly repeatedly, and it's important that each execution of the method retains its own copy of the b variable. If there was just a single storage space for the b variable in memory, then recursion wouldn't be possible.2

So, the storage for variables has to be dynamically provided - each time a method is entered, new storage has to be made available for the local variables. And one particularly common way to provide such storage is via a "stack frame" or "activation record". How much storage is actually required is subject to a complex discussion involving optimization and variable lifetimes, but in the trivial case we say that the stack frame contains enough storage space for each local variable.

However, const locals are special variables - because they don't vary. As an optimization, then, we can just store one copy of this variable somewhere, and every instance of Compute that is running can just reference that single copy.


1Here, it's trivially recursive, but it need not be so - the recursion could be hidden through a number of intermediate method calls to other methods.

2Nor could we allow the method to be called by multiple threads.

Damien_The_Unbeliever
  • 234,701
  • 27
  • 340
  • 448