C Programming/Storage Class

From Chorke Wiki
Revision as of 05:16, 5 February 2018 by Shahed (talk | contribs) (Created page with "A storage class defines the scope (visibility) and life-time of variables and/or functions within a '''C Program'''. They precede the type that they modify. We have four diffe...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

A storage class defines the scope (visibility) and life-time of variables and/or functions within a C Program. They precede the type that they modify. We have four different storage classes in a C program :

  1. auto
  2. register
  3. static
  4. extern

The auto Storage Class

The auto storage class is the default storage class for all local variables.

{
   int mount;
   auto int month;
}

The register Storage Class

The register storage class is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the register size (usually one word) and can't have the unary '&' operator applied to it (as it does not have a memory location).

{
   register int  miles;
}

The static Storage Class

The static storage class instructs the compiler to keep a local variable in existence during the life-time of the program instead of creating and destroying it each time it comes into and goes out of scope. Therefore, making local variables static allows them to maintain their values between function calls.

The static modifier may also be applied to global variables. When this is done, it causes that variable's scope to be restricted to the file in which it is declared.

In C programming, when static is used on a global variable, it causes only one copy of that member to be shared by all the objects of its class.

//main.c
#include <stdio.h>

void func(void);

//global variable
static int count = 5;

int main()
{
    while(count--){
        func();
    }
    return 0;
}

void func( void )
{
    //local variable
    static int i = 5;
    i++;
    printf("i is %d and count is %d\n", i, count);
}