Wednesday, 2 January 2013

Storage classes in C

A rather surprising yet monumental discovery of a concept in C that I knew little about. Storage classes or groups are all about the extent to which definition of a variable is valid in the context of a C program.

There are 4 storage classes in C:

1) auto: the default class when a user does not give any storage class specifier, this is tantamount to a regular variable declaration.

e.g: int a or auto int a are both equivalent to each other

2) static: fairly intuitive to all Java programmers. A static specifier is used for a global variable declaration so that the value of the variable is initialized only once at run-time and is immune to any number of function calls that follow.

e.g.

static int count=10;
void function_A()
{
     count=count+1; 
     printf("%d",count);
}

int main()
{
for(int i=0;i<5;i++)
      function_A();
}

The output of the above program will read:
11
12
13
14
15

3) extern: This is one of the most interesting and least known C concepts to most Java programmers. A variable whose storage class has been defined as extern may be accessed from a file external to the one where it has been defined. Another point to be noted is that such variables are global. extern is nothing but a static variable that can be seen and accessed from multiple files.

e.g
//Program 1
int A=0;
int main()
{
       function_A();
}

//Program 2

extern int A;
void function_A()
{
      printf("A=%d",A);
}

4) register: Another cool concept that lets you store variables in register rather than in physical memory. This of course lets you tap into the higher speed of registers, commonly called associative access. This of course does imply that the variable size is limited by size of the register which is used to house the variable. The storage class specification has a fairly simply syntax which is given below:

{
    register int A;
}


Hope this post was informative. Stay tuned for more updates. You may follow me on twitter. My twitter handle is @imancrsrk. You can also search for my science and tech group, GIC: Glean Info Club on facebook.






No comments:

Post a Comment