user3040663
user3040663

Reputation: 41

How does the local static variables are stored

If I declare a global variable as static it will be stored in data segment. And all the functions in that file can access it. no issues so far....

If, inside a function if we declare a static variable, as shown below: int foo() { static int a; . . }

so this variable "a" also stored in data segment (please correct me if I am wrong).

my question is, if the global static variable which is stored in data segment is accessible across the functions. But the static variable which is defined inside the function which is also stored in data segment, is not accessible across the functions, why?

Upvotes: 2

Views: 264

Answers (2)

user1814023
user1814023

Reputation:

That is because of SCOPE

Scope is the region or section of the code where a variable can be accessed. There can be

  1. File Scope
  2. Function Scope
  3. Block Scope
  4. Program Scope
  5. Prototype Scope

Example

#include<stdio.h>
#include<conio.h>

void function1()
{
    printf("In function1\n");
}

static void function2()
{
    printf("In function2\n");
    {
        int i = 100;
Label1: 
        printf("The value of i =%d\n",i);
        i++;
        if(i<105)
        goto Label1;
    }
}

void function3(int x, int y);

int main(void) 
{
    function1();
    function2();
    getch();
    return 0;
}

In the example,

  • ‘function1()’ has ‘Program Scope’.
  • ‘function2()’ has ‘File Scope’.
  • ‘Label1’ has ‘Function Scope’. (Label names must be unique within the functions. ‘Label’ is the only identifier that has function scope.
  • Variable ‘i’ has ‘Block Scope’.
  • Variable ‘x’ and ‘y’ has ‘Prototype Scope’. There cannot be two variables with the name ‘x’ or ‘y’ in the function parameter list.

Upvotes: 2

woolstar
woolstar

Reputation: 5083

Its just a rule the compiler and linker implement. For one thing you can have multiple static variables in different functions with the same name.

Upvotes: 1

Related Questions