A variable is the 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 symbols so that it can be easily identified.

Example:- Int a=10; char a=‘c’ etc.

Rules for defining variables

  • A variable can have alphabets, digits, and underscore.
  • A variable name can start with the alphabet, and underscore only. It can't start with a digit.
  • No whitespace is allowed within the variable name.
  • A variable name must not be any reserved word or keyword, e.g. int, float, etc.

Valid variable names Ex-:

int a;  
int _ab;  
int a30;  

Invalid variable names Ex-:

int 2;  
int a b;  
int long;  

There are Five  Types of Variables

  1. Local Variable
  2. Global Variable
  3. Static Variable
  4. Automatic Variable
  5. External Variable

1. Local Variable

A variable that is declared inside the function or block is called a local variable.

Ex:-
#include<stdio.h>
#include<conio.h>
Void main()
{
     void fun()
    {  
        int x=10;  //local variable  
    }
  getch();
}  

2. Global Variable

A variable that is declared outside the function or block is called a global variable. Any function can change the value of the global variable. It is available for all the functions.

Ex:-
#include<stdio.h>
#include<conio.h>
Int a=10; //Global Variable
Void main()
    printf(“%d”,a); 
    fun();
    getch();
}  
void fun()
 {  
        printf(“%d”,a); 
 }

3. Static Variable

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

Ex:-
#include<stdio.h>
#include<conio.h>
Void main()
    fun();
    fun();
    fun();
    getch();
}  
void fun()
 {  
   int x=10;  //local variable  
   static int y=10;  //static variable  
   x=x+1;  
   y=y+1;  
        printf(“%d %d”,x,y); 
 }

4. Automatic Variable

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

Ex:-
#include<stdio.h>
#include<conio.h>
Void main()
int x=10;//local variable (also automatic)  
auto int y=20;//automatic variable  
getch();
}  

5. External Variable

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

Ex:-
#include<stdio.h>
#include<conio.h>
Int a=10;
Void main()
    extern int a=10;//external variable (also global) 
    printf(“%d”,a); 
    getch();
}  

Watch the Video Lecture


            Previous                                                                                                                       Next