Variable : Local Global Static

What is Variable Scope – A scope is a region of the program and broadly speaking there are three places, where variables can be declared − Inside a function or a block which is called local variables, In the definition of function parameters which is called formal parameters. Outside of all functions which is called global variables.

According to the variable scope , we have to type of variables 

  • Local Variables
  • Global Variables

Let’s Recap 

  • Local Variable
    • When variable declare within a function or block statement , that variable is called local variables.
    • We can declare Local Variable of SAME NAME with different function body or block statement . 
    • The scope of local variable is not only confined within function body but also block statement.
  • Global Variable
    • By default , value or data of global variable is Zero.
    • If we change or update any global variable in one function and then we use that global variable in another function , we will get the previous update or change in the second function.
    • Compile will show no error , if we declare local and global variable with the same NAME. But in these case , the variable which is local will work in function body or block statement.

 

Static Variable

Let’s assume we have a single function and there is a local variable . For the first time we call that function and update that local variable form ( assume ) 0 to 1 and print it . Again we call that function and again it print 1 as we update it from 0 to 1 . Now , if we want that, when we call for the second time of any function , the local variable of that function must give its previous updated value . Means, at the first call it update 1 and in the second call it should give us 2 or update from 1 to 2 . For these , we need to declare that local variable as static .

static int a ; // declaration

We simply write static keyword for these operation . And we get the update value each time when we call that function.We can than count , how many times a function be called . These seems not necessary feature but it does need . We’d have fully understand how it operates , because we’ll use it a lot.

Leave a comment