Reputation: 41
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
Reputation:
That is because of SCOPE
Scope is the region or section of the code where a variable can be accessed. There can be
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,
Upvotes: 2
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