Static and Register variables in C

Interview Questions
  • What is static variable in C
  • What are the properties of a register variable in C
  • What is the difference between variable declaration and variable definition in C

What is static variable in C

Static variables retain their values between function calls. We can declare static variable by adding static keyword before data type in variable declaration statement.

static data_type variable_name;
For Example, 
    static int sum;
  • Static keyword has different effect on local and global variables.
  • For local static variables, compiler allocates a permanent storage in heap like global variable, so that they can retain their values between function calls. Unlike global variables, local static variables are visible only within their function of declaration.
  • For global static variables, compiler creates a global variable which is only visible within the file of declaration.
  • Variables declared static are initialized to zero(or for pointers, NULL) by default.


What are the properties of a register variable in C

  • The scope of register variables are same as automatic variables, visible only within their function.
  • You a only declare local variables and formal parameters of a function as register variables, global register variables are not allowed.
  • Declaring a variable as register is a request to the compiler to store this variable in CPU register, compiler may or may not store this variable in CPU register(there is no guarantee).
  • Frequently accessed variables like loop counters are good candidates for register variable.


What is the difference between variable declaration and variable definition in C

Declaration of a variable declares the name and type of the variable whereas definition of a variable causes storage to be allocated for the variable. There can be more than one declaration of the same variable but there can be only one definition for the variable.

In most cases, variable declaration and definition are same. However you can declare a variable without defining it by preceding a variable name with extern specifier.


Related Topics
What is modifier in C and different types of modifiers.
What is global variable in C
What is local variable in C
What is constant in C and Different Types of Constants.
What is the difference between pre (++var) and post(var++) increment operator.
Why is default statement used in switch case in C
Can we use negative array indexes in C.
What is const pointer in C
What is NULL pointer in C.
What is Wild pointer in C.