C Language: Storage classes

Storage Classes in C

Storage Classes are used to describe the features of a variable/function. These features basically include the scope, visibility and life-time which help us to trace the existence of a particular variable during the runtime of a program.

A variable’s storage class tells us the following.

1. Where the variables would be stored.

2. What will be the initial of the variable, if the initial value is not specifically assigned? (i.e. the default initial value).

3. What is the scope of the variables, i.e. in which part of the program or the functions the value of the variables would be available?

4. What is the life of the variable, i.e. how long would the variable exist?

These are four storage classes in C:

(a) Automatic storage classes.
(b) Register storage classes.
(c) Static storage classes.
(d) External storage classes.

Automatic storage classes.

The keyword “auto” is used to declare a variable of the automatic storage class. (Mentioning keyword auto is optional).

Example:

auto int a;

int a; (keyword auto is optional)

Properties

Storage Memory
Default initial value An unpredictable value, which is called a garbage value.
Scope Local to the block in which the variables is defined.
Life Till the control remains within the block in which the variable is defined.

Example:1
To display the default values of variables

Note: in the output, two garbage values will be displayed
as automatic variables by default store garbage values

#include<stdio.h>
int main()
{
  auto int i,j;
  printf("\n %d %d",i,j);
  return(0);
}

Example:2
To display scope and life of variables

#include<stdio.h>
int main()
{
auto int a=10;
  {
     {
       {
	 printf("%d\n",a); //1
       }
       printf("%d\n",a);//2
     }
    printf("%d\n",a);//3
   }
printf("%d\n",a); //4
return(0);
}

/* Output */
10
10
10
10

Example:3
To display scope and life of variables

Note:
Ques:Can we declare two or more variable having same name?

Sol:Yes, we can have any number of variables having the
same name but they have to be declared in different blocks as shown below.

#include<stdio.h>
int main()
{
auto int a=10;
	{
	auto int a=20;
		{
		auto int a=30;
			{
			auto int a=40;
			printf("%d\n",a);//1
			}
		printf("%d\n",a);//2
		}
	printf("%d\n",a);//3
	}
printf("%d\n",a); //4
return(0);
}
/* Output */
40
30
20
10

C Language Programming Tutorial

C Language Tutorial Home     Introduction to C Language     Tokens     If Condition      goto statement and Labelname     Switch Statements     For loop     While Loop     Do while loop     break and continue     Functions     Recursion     Inbuild Functions     Storage Classes     Preprocessor     Arrays     Pointers     Structures and Unions     File Handling     Projects