Skip to main content

Storage classes in C, Scope and Life Time

In C variables are declared by the type of data they can hold. During the execution of the program, these variables may be stored in the registers of the CPU or in the primary memory of the computer. To indicate where the variables would be stored, how long they would exist, what would be their region of existence, and what would be the default values, C provides four storage class specifiers that can be used along with the data type specifiers in the declaration statement of a variable. These four storage class specifiers are 
Automatic
External
Register
Static

Storage classes specify the scope, lifetime and binding of variables.

To fully define a variable, one needs to mention not only its ‘type’ but also its storage class.

A variable name identifies some physical location within computer memory, where a collection of bits are allocated for storing values of variable.

Storage class tells us the following factors −

Where the variable is stored (in memory or cpu register)?
What will be the initial value of variable, if nothing is initialized?
What is the scope of variable (where it can be accessed)?
What is the life of a variable?

Lifetime
Life Time - Life time of any variable is the time for which the particular variable outlives in memory during running of the program.

The lifetime of a variable defines the duration for which the computer allocates memory for it (the duration between allocation and deallocation of memory).

In C language, a variable can have automatic, static or dynamic lifetime.

Automatic − A variable with automatic lifetime are created. Every time, their declaration is encountered and destroyed. Also, their blocks are exited.An automatic variable has a lifetime that begins when program execution enters the function or statement block or compound and ends when execution leaves the block. Automatic variables are stored in a "function call stack".
StaticA variable is created when the declaration is executed for the first time. It is destroyed when the execution stops/terminates.A static variable is stored in the data segment of the "object file" of a program. Its lifetime is the entire duration of the program's execution.
Dynamic − The variables memory is allocated and deallocated through memory management functions.
The lifetime of a dynamic object begins when memory is allocated for the object (e.g., by a call to malloc() or using new) and ends when memory is deallocated (e.g., by a call to free() function ). Dynamic objects are stored in "the heap".

Scope of a variable
Scope - The scope of any variable is actually a subset of life time.A variable may be in the memory but may not be accessible though. So, the area of our program where we can actually access our entity (variable in this case) is the scope of that variable.

The scope of any variable can be broadly categorized into three categories :
Global scope : When variable is defined outside all functions. It is then available to all the functions of the program and all the blocks program contains.
Local scope : When variable is defined inside a function or a block, then it is locally accessible within the block and hence it is a local variable.
Function scope : When variable is passed as formal arguments, it is said to have function scope.

Summary of Storage Classes, Scope and Life Time

There are four storage classes in C language −
Storage ClassStorage AreaDefault initial valueLifetimeScopeKeyword
AutomaticMemoryGarbage valueTill control remains in blockLocalauto
RegisterCPU registerGarbage valueTill control remains in blockLocalregister
StaticMemoryZeroValue in between function callsLocalstatic
ExternalMemoryzeroThroughout program executionGlobalextern
The storage class specifier precedes the declaration statement for a variable.
Eg:
auto int x;
extern int y;
register int z;
static int s;

We will discuss these storage class one by one

1.Automatic storage class
By default, all variables declared within the body of any function are automatic. The keyword auto is used in the declaration of a variable to explicitly specify its storage class. Even if the variable declaration statement in the function body does not include the keyword auto, such declared variables are implicitly specified as belonging to the automatic storage class.

These variables are created automatically, when the function in which it is declared is evoked. These variables are created in primary memory and behaves as local variables of the function. Their region of use is limited within the function body and by default they are not initialized.

The following program explains the use of automatic and global variables and their scope.

#include <stdio.h>
int i=10;
void f1()
{
auto int i=20;
printf(“The value of i in function f1 is =%d”,i);
}
void f2()
{
printf(“The value of i in function f2 is=%d”,i);
}
int main()
{
f1(); /* prints 20 ..uses the local variable*/
f2(); /prints 10 ..uses the global variable*/
}
2.External Storage class
A program in C, particularly when it is large, can be broken down into smaller programs. After compiling these, each program file can be joined together to form the large program. These small program modules that combine together may need some variables that are used by all of them. This provision can be made by specifying these variables as external storage class variable. These variables are global to all the small program modules that are formed as separate files.

The keyword for declaring such global variable is extern. Such global variables are declared like any other variable in one of the program modules while the declaration of these variables are preceded with the keyword extern in all other combining program modules. The program modules may also be a function or a block. These variables remain in existence as long as the program in execution. These variables are stored in primary memory and their default value is zero.

Example:

/**** program file prgm1.c ****/
#include <stdio.h>
int i;   // global variable
void show(void);
int main()
{
show(); /* show() function in another program file */
printf(“The value of i in prgm1.c=%d”,i);
}
/***** program file prgm2.c *****/
extern int i;
void show()
{
i=20;
printf(“The value of i in progm2.c=%d”,i);
}
Output:
The value of i in progm2.c=20
The value of i in progm1.c=20
3.The Register Storage Class
The variables stored in register of the CPU are accessed in much lesser time than those stored in the primary memory. To allow the faster access time for variable, the register storage class specifier is used. In most C compilers register specifier can only be applied to int and char.ANSI C has broadened its scope.The default value of these variable is garbage and their use is restricted within the region of a function or a block where it has been declared.
Example:
#include <stdio.h>
int power(int,register int);
int main()
{
int x=4;
int k=3;
int p;
p=power(x,k);
printf(“The value of %d power %d is=%d”,x,k,p);
}
int power(int x,register int k)
{
register int temp;
temp=1;
for(;k;k- -) temp=temp*x;
return temp;
}
Output:
The value of 4 power 3 is 64
4.The Static Storage Class
The use of static storage class specifier makes a variable a permanent variable within a specified region. Two kinds of variables are allowed to be specified as static variables: local variables and global variables. The local variables are also referred to as internal static variables while the global variables are also known as external static variables. The default value of the static variable is zero.

A static local variable is allotted a permanent storage location in the primary memory. This variable is usable within functions or blocks where it is declared and preserves its previous value held by it between function calls or between block re-entries. However once a function is invoked, the static local variable retains the value in it and exists as long as the main program in execution.

The external static variables in a program file are declared like global variables with the keyword static preceding its declaration statement. These variables can be accessed by all functions except those functions defined earlier in the same file or not accessible to functions defined in other files although these may use the extern keyword. These variables exist throughout the period of the main program in execution.

Example:
#include <stdio.h>
void show(void)
{
static int i;
printf(“The value of static variable i=%d”,i);
i++;
}
int main()
{
printf(“First call of show function\n”);
show();
printf(“Second call of show function\n”);
show();
printf(“Third call of show function\n”);
show();
}

Output:
First call of show function
The value of static variable i=0
Second call of show function
The value of static variable i=1
Third call of show function
The value of static variable i=2

Comments

Popular posts from this blog

KTU Mandatory C programs for Laboratory and Solutions

LIST OF LAB EXPERIMENTS 1. Familiarization of Hardware Components of a Computer 2. Familiarization of Linux environment – Programming in C with Linux 3. Familiarization of console I/O and operators in C     i) Display “Hello World”     ii) Read two numbers, add them and display their sum     iii) Read the radius of a circle, calculate its area and display it 4. Evaluate the arithmetic expression ((a -b / c * d + e) * (f +g))   and display its solution. Read the values of the variables from the user through console 5. Read 3 integer values, find the largest among them. 6. Read a Natural Number and check whether the number is prime or not 7. Read a Natural Number and check whether the number is Armstrong or not 8. Read n integers, store them in an array and find their sum and average 9. Read n integers, store them in an array and search for an element in the    array using an algorithm for Linear Search 10.Read n integers, store them in an array and sort the elements in t

PROGRAMMING IN C KTU EST 102 THEORY AND LAB NOTES

PROGRAMMING IN C  KTU  EST 102  THEORY AND LAB   COMMON FOR ALL BRANCHES About Me Syllabus Theory Syllabus Lab Model Question Paper EST 102 Programmin in C University Question Papers  and evaluation scheme   EST 102 Programming in C  Introduction( Lab) Introduction to C programming Linux History and GNU How to create a bootable ubuntu USB stick Installing  Linux Install Linux within  Windows Virtual Box and WSL Linux Basic Features and Architecture Basic Linux Commands Beginning C Programming Compiling C programs using gcc in Linux Debugging C program using gdb Module 1: Basics of computer hardware and software          Module-1 Reading Material Basics of Computer Architecture Hardware and Software System Software and Application Software  Programming Languages ( High level, Low level and Machine Language) and Translators ( Compiler, Interpreter, Assembler) Algorithm, Flowcharts and Pseudo code Program Development Structured Programming Basics of hardware ( video) Know about Motherboar