Home > Enterprise >  Why local variables are not accessible from other functions?
Why local variables are not accessible from other functions?

Time:10-18

I'm currently learning about computer memory and asking questions to myself to understand it better.

I learned about how a new space is allocated in the stack whenever a function is called. But why we can't reach local variables even though they are still on the stack? What is it that prevents me from accessing them while they are still on the stack?

Consider the following code (Please look at the comments):

class Program
{
    public static void Main()
    {
        int number = 5; 

        Method();

    } //<------ number variable will be stored in the stack until the program reaches here.

    public static void Method()
    {

        // number=5 variable is still on the stack so why can't I reach it here?

        number = 10; // throws an error because it's not defined in this scope but it's still on the stack.

        int anotherNumber = 2; 
    }
}

CodePudding user response:

If that code could compile (i.e. if you comment out number = 10;), the variable number would likely not even be on the stack in a Release build because it's unused and the optimizer would realize that.

C# uses scoping for variables, and the scope of the variable number is the Main() method. If you define it inside the class instead, it'd be a class member and would be accessible also from the method Method(). As a general rule of thumb, though, always try to limit the scope of variables.

class Program
{
    int number = 5; // class member

    public static void Main()
    {
        Method();    
    }

    public static void Method()
    {    
        number = 10; // no error anymore

        int anotherNumber = 2; 
    }
}

CodePudding user response:

In C and languages derived from it, functions are separately compiled so they cannot "see" the local variables of each other. This is a design decision.

In Pascal and languages derived from it, this is made possible by allowing nested function declarations. A function declared inside another sees the local variables of the latter as global ones.


But beware that via mutual and recursive calls, the same variable can exist at several places in the stack.

  • Related