Monday, September 21, 2015

C Language : Static


So in the last post , we have seen the EXTERN.  In this post we will see STATIC .

We can define STATIC in global variables or local variables.

If we define STATIC in global variables, then the global variables scope will be that file only.
So even if you have extern that variable in some other file , then error will come.

Program 1)

static1.c

#include<stdio.h>

static int a=10;

int main()
{
func()
}

static2.c

extern int a;

void func()
{
printf("%d",a);
}

now if you GCC and compile both files separately then , there will be no COMPILE ERROR.
But on creating object file, LINK ERROR will come. Since a is not visible outside the static1.c

Program 2)

static1.c

#include<stdio.h>

static int a;
a=10;

int main()
{
func()
}

This will give COMPILE ERROR, since non static definition cannot follow the static definition.



Now lets see what happens when static is defined with local variable.

Program 3)

static1.c


#include<stdio.h>

int main()
{

func();
func();
}

int func()
{
static int a;
a=10;
a++;
printf("%d",a);
}

the output of the function will be 11 and 11

Since static variable are assigned value at time of declaration. If we assign value after declaration, then everytime func is called , that value will be put in the function.

Program 4)

static1.c


#include<stdio.h>

int main()
{

func();
func();
}

int func()
{
static int a=10;
a++;
printf("%d",a);
}

this will behave as it should be , output will be 11 and 12.

What will happen if static variable is not initialized.

All static and extern variables will be initialized to zero if not explicitly assigned some value.

No comments:

Post a Comment