Thursday, 21 September 2017

C++ program to demonstrate the use of static variable

/*
 C++ program to demonstrate the use of static variable 
*/
#include "iostream"
using namespace std;

int num;
void myfunc();

int main(){

 num = 10;
 cout<<"Num in main: "<<num;
 myfunc();
 myfunc();
 cout<<"\n Num at the end: "<<num; 
 return 0;
}

void myfunc(){
 static int num=20;
 cout<<"\nNum: "<<num;
 num += 10;
}

/*
--Static variable value is preserved within a function call. 
--Global variable value is preserved among the different function calls as well. 
--Means static variable scope is local. 
 
[pavan@localhost Practise]$ g++ StaticVariable.cpp
[pavan@localhost Practise]$ ./a.out 
Num in main: 10
Num: 20
Num: 30
 Num at the end: 10[pavan@localhost Practise]$ 

*/

No comments: