Types of Variables in C

There are many types of variables in C. We and use depending on situation . Lets try to understand the types of variables in C.


There are many types of variables in c

  local variable

  global variable

  static variable

  automatic variable

  external variable

Local Variable

Local Variable are the variables which are defined inside function or block is called Local Variables. It must be declared at the start of the block


#include 
void show()
{
    int a=50;//local variable
    printf("value of local variable %d ",a);

}
int main()
{
    show();
    return 0;
}
value of local variable 50

Global Variable

A variable that is declared outside the function or block is called global variable. Any function can change the value of the global variable. It is available to all the functions.It must be declared at the start of the block.


#include .
int myvariable=50;//global variable
void show()
{
    int a=50;//local variable
    myvariable=60;
    printf("value of local variable %d ",a);

}
int main()
{
    show();
    printf("\n");//changing the line
    printf("value of global variable %d",myvariable);
    return 0;
}
value of local variable 50
value of global variable 60

Static Variable

Variable declare with static keyword is called Static Variable. static variable retain the value between multiple function calls.


#include .
static int myvariable = 50; //global variable

void show() {
    int i = 50;
    static int j = 60; //static variable retain its value 
    i = i + 1;
    j = j + 1;
    printf("i = %d ,", i);
    printf("j = %d", j);
    printf("\n");


}

int main() {
    int k = 1;
    for (k = 1; k <= 10; k++) {
        show();
    }
    return 0;
}
i = 51 ,j = 61
i = 51 ,j = 62
i = 51 ,j = 63
i = 51 ,j = 64
i = 51 ,j = 65
i = 51 ,j = 66
i = 51 ,j = 67
i = 51 ,j = 68
i = 51 ,j = 69
i = 51 ,j = 70

In above example variable j is static and retain its value between multiple function calls.

Automatic Variable

All variables in C that is declared inside the block, are automatic variables by default. By we can explicitly declare automatic variable using auto keyword


#include 
int main()
{
    int k=100;//local variable  / automatic variable
    printf("value of automatic variable %d",k);
    return 0;
}

output: value of automatic variable 100

External Variable

We can share a variable in multiple C source files by using external variable. To declare a external variable, you need to use extern keyword.

Create a header file . File : function.h

extern int myvariable=9764;

Create main() function in other file


#include 
#include "function.h"
int main()
{
    printf("value of extern variable %d",myvariable);//printing the value of extern variable myvariable
    return 0;
}
value of extern variable 9764
woman avatar