what are static variables and globals

In c programming static variable is a special type of variable can retain its value between invocations .It has two types :
1. Static to function or control block
2. Static to the file

If it is static to function it will retain the value when the function is called again and again .

Eg
Void foo()
{
Static int a;
a++;
printf(“%d\n”,a);
}


In consecutive calls it will have values 1 , 2 …..
But cant be accessed outside of the function.
In the static to the file scenario the variable is commonly declared at the top like the globals .
it is accessible to all functions but it will retain the value.



Difference between the globals , when static is in a header file it will have 1 copy per file that include the header.
Eg:

-----------------test.h-----------------

static int var;

----------------- mainfile.c ----------------------
#include
#include ”test.h”

Int main (){
printf("var in %s: %d\n ", __FILE__, ++var);
in_file2();


}

---------------------file2.c----------
in_file2{
printf("var in %s: %d\n",__FILE__, ++var);
}

Compile as :
gcc -o statictest mainfile.c file2.c
Output:
./statictest
Output:
~/test $ ./statictest
var in main.c: 1
var in file2.c: 1
Same var if only a global the output will be :
var in main.c: 1
var in file2.c: 2

Comments

Popular posts from this blog

8051 Development Setup:MIDE-51 Installation

Nokia dot Matrix LCD Interfacing with 89c51( 8051 core)