SQL

Sunday, 8 March 2015

Static and non static local variables

The static storage class instructs the compiler to keep a local variable in existence during the life-time of the program instead of creating and destroying it each time it comes into and goes out of scope. Therefore, making local variables static allows them to maintain their values between function calls.

Example 1:


#include 
#include 
 using namespace std;
// Function declaration
void func(void);

static int count = 10; /* Global variable */

main()
{
    while(count--)
    {
       func();
    }
    return 0;
}
// Function definition
void func( void )
{
    static int i = 5; // local static variable
    i++;
    cout << "i is " << i ;
   cout << " and count is " << count << endl;

}

Output:

i is 6 and count is 9
i is 7 and count is 8
i is 8 and count is 7
i is 9 and count is 6
i is 10 and count is 5
i is 11 and count is 4
i is 12 and count is 3
i is 13 and count is 2
i is 14 and count is 1
i is 15 and count is 0
But if you erase the static storage class the the function always find i = 5. let's see it:
Example 2:
#include <iostream>
#include <iomanip>
// Function declaration
void func(void);
 
static int count = 10; /* Global variable */
 
main()
{
    while(count--)
    {
       func();
    }
    return 0;
}
// Function definition
void func( void )
{
    int i = 5; // local static variable
    i++;
    cout << "i is " << i ;
    cout << " and count is " << count << endl;
}
output:
i is 6 and count is 9
i is 6 and count is 8
i is 6 and count is 7
i is 6 and count is 6
i is 6 and count is 5
i is 6 and count is 4
i is 6 and count is 3
i is 6 and count is 2
i is 6 and count is 1
i is 6 and count is 0

Post a Comment