adsense


Friday, 20 November 2015

C++ LANGUAGE STATIC STORAGE CLASS PAGE 35

COMPUTER LANGUAGES HTML,C,C++.JAVA,.NET AND MULTIMEDIA basics and programs click home button



C++ LANGUAGE STATIC STORAGE CLASS






The static Storage Class 


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. 
The static modifier may also be applied to global variables. 
When this is done, it causes that variable's scope to be 
restricted to the file in which it is declared. 

In C++, when static is used on a class data member, it causes 
only one copy of that member to be shared by all objects of its class. 

#include <iostream> 
  
// 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++; 
    std::cout << "i is " << i ; 
    std::cout << " and count is " << count << std::endl; 
} 
When the above code is compiled and executed, it produces the following result: 
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 


No comments: