Life of variable

Life of variable



Each and every variable we declare in C has its own lifetime.

There are 3 types of variables:


  •  Local variables: These variables are variables which are declared within a block and as soon as complier comes across this variable it is declared. Its life is upto point where curly braces end. Accessing it after that gives an error.
  • Block variables: These variables are same as local variable but they are inner block variables. Its life is upto point where curly braces end. Accessing it after that gives an error. (see example below)
  • Global variables: These variables can be accessed at any point of program and has no bound of any curly braces. We use keyword called ‘global’ to initialize this variables.

Example illustrating life of variables:

#include<stdio.h>
global int x;                       //Global variable
void main()
{
int y;            //Local variable   
…..
               {
               int z=10;                             //Block variable
               …..
               }
printf(“%d”,z);                   //This will give an error as z variable is not accessible outside its block
}

No comments:

Post a Comment