Over 10 years we help companies reach their financial and branding goals. Engitech is a values-driven technology agency dedicated.

Gallery

Contacts

411 University St, Seattle, USA

engitech@oceanthemes.net

+1 -800-456-478-23

Daily Coding Miscellaneous

Static Variables in C

Static is a keyword in the c/cpp language. It is a storage class specifier that can be applied to any data type. A static keyword can be used with both variables and functions.

  • The static keyword tells the compiler to make the variable or function limited to scope but allows it to persist throughout the life of a program. The static keyword limits the scope of variables or functions to the current source file only. So static keyword helps in hiding the data to one source file only. 
  • Static words help in achieving encapsulation in c language.

In this blog, we are going to cover the use of static keywords with variables.

  1. Static variables are stored in BSS or data segment of the C program Memory Layout. The BSS segment contains the uninitialized data. The DATA segment keeps the initialized data.
  2. The static variable is only initialized once, if it is not initialized then it is automatically initialized to 0.

    void demo(int value)

    {

    static int count  = 0;

    count = value;

    cout<<count;

    }

    count = value: is not initialization, it is an assignment. Static can be assigned as many times as we wish.

    static int count = 0: is initialization & that happens only once for static variables.

We can have static global variables or static local variables.

Static local variables

Static variables are able to retain their value b/w function calls. Static keywords, when used with variables inside the function, are then called static local variables. 

Static global variables

The static keywords when used with variables outside the functions,  are then called static global variables.

Static global variables help in achieving enumeration, that is they make the scope of the variable limited to the present file only.

References:

Author

Kunal

Leave a comment

Stay Updated With Us

Error: Contact form not found.

      Blog