Storage classes in C - static

After you understood extern storage class in the previous tutorial lets understand the static storage class.

There are three terms you should understand first

1) Program

A program is all the code that you write to solve a given problem. When you write code you divide it into many files to manage it properly. Also in every file you divide the code into many functions.

2) File

When you write code you put it inside a file. A c program file ends with .c extension. Inside the file you divide the code into functions.

3) Code block

A code block starts with { and ends with }

Visibility of variables

From our earlier tutorials you learnt that variables are of two types - local and global.

A variable declared outside the function is global and it is available to the all the code in your program. Even if the code is written in other files.

A variable declared inside a code block is called local variable and is only available inside that code block.

static variables

1st important thing to know

static variables remember their value throughout the program execution. Even if you make a local variable static it will remember its value throughout the programe execution. It will not forget its value even after the code goes out of its code block.

Look at the code below

void PrintNumber()  
{      
    static int i = 0;      // i will be initialized to 0 only once      
                                // next time you call the function it will remember      
                                // its previous value;        
    i = i+1;        
    printf("%d",i);  
}    

void main( )  
{      
    int j=0;        
    
    for(j=0 ; j<5 ; j++)      
    {          
        PrintNumber();      
    }      
    
    return 0;  
}

The output of the program is

1  2  3  4  5

Carefully note that calling PrintNumber() function in the loop does not make the value of i zero every time. It remembers its last incremented value.

If you mark variable i as non static the output of the above program will be

1  1  1  1  1

This is because the non static variables do not remember their values. They are initialized every time a function is called.

2nd important thing

When you mark a global variable as static its visibility is reduced. A static global variable is only visible inside its file and not available to code in the other files. So a static global variable has a file scope. A non static global variable has global scope.

Related Questions

Quick Links

E-Magazines

@

Total Followers
Study Group Created
Study Group Joined
Following Teacher
Following Organization
Blog Articles Added
Questions Asked
Questions Answered
Jobs Posted
Total Members in Group
Questions asked by members
Tasks added in this Group

Please wait..

Ok

Login to Open ESchool OR Create your account    Login   SignUp