variable is a name of the memory location. It is used to store data. Its value can be changed, and it can be reused many times.

It is a way to represent memory location through symbol so that it can be easily identified.

Let’s see the syntax to declare a variable:

type variable_name;
    or for multiple variables:
  type variable1_name, variable2_name, variable3_name;

There are 5 types of variables in C.

1. Local Variable

A local variable is a variable which is defined and used inside a particular block of code. There’s no existence of it outside of the block. Like all variables, local variables also needed to be declared before use.

Example
#include <stdio.h>
void function() {
int x = 10; // local variable
}

int main()
{
function();
}

In the above code variable x has no existence outside of function. If used it will give an declaration error.

2. Global Variable

A variable that is defined outside of the function or block is called global variable. It can be accessed by any block or function. Any function can change the value of the global variable.

It should be declared at the start of program.

Example

int value=20;//global variable  
void function1()
{  
      int x=10;//local variable  
}

3.Static Variable 


A variable that retains its value between multiple function calls is known as static variable.  It is declared with the static keyword. 

Example- 

#include <stdio.h>
void function(){
int x = 20;//local variable
static int y = 30;//static variable
x = x + 10;
y = y + 10;
printf("\n%d,%d",x,y);
}
int main() {

function();
function();
function();
return 0;
}

Output

30,40
30,50
30,60

In the above example , local variable will always print same value whenever function will be called whereas static variable will print the incremented value in each function call.

Automatic Variable

When we declare a variable inside the block, it’s automatic variables by default. We can explicitly declare an automatic variable using auto keyword.

void main(){    
          int x=10;//local variable (also automatic)  
          auto int y=20;//automatic variable  
} 

External Variable

When we need a variable such that it has to be used among several C source files we define a variable as external variable. It can be defined as external variable by using extern keyword.

Example:

myfile.h
extern int x=10;//external variable (also global)
program1.c
#include "myfile.h"  
  #include <stdio.h>  
  void printValue(){  
  printf("Global variable: %d", global_variable);  
  }

In the above example x is an external variable which is used in multiple files.

For more Programming related blogs Visit Us Geekycodes . Follow us on Instagram.

Leave a Reply