C++ static variables

The static keyword is used commonly to enable a local variable declared in a function to increase its life time. Normally when a local variable is declared in a function, its life ends when the function ends. To allow the variable to return its current value, you need to declare it with the static keyword as you see in the code example below. Static variables stay in the program until the program ends. For a global variable, by declaring it with static keyword, the global variable is known only in the file in which it is declared.
Note: all static variables are automatically initialized to zero.

#include <conio.h>
#include <cmath>
using namespace std;

void mul(int a){
   static int s=2;
   s=s*a;
   cout<<s<<endl;
   }

int main(){
   mul(10); //first call output : s=20
   mul(10); //next call output: s=20*10=200
  
   getch();
   return 0;
}

For a static class member, you do not need to create an object to access it.
#include <iostream>
#include <conio.h>
#include<test.h>
using namespace std;
class Point{
    private:
          int x,y;
    public:
          static void viewName(){
               cout<<"Class name: Point"<<endl;
               }
          static string date;
          
    public: void setPoint(int cx,int cy){
         x=cx;
         y=cy;
         }
    };
    
string Point::date="01-05-2013"; //initialize static data member

int main(){
   Point p; //create Point object to access non-static member
   p.setPoint(10,200);
   Point::viewName(); //no need to create object to access
   //viewName and date because they are static.
   cout<<"Created date:"<<Point::date<<endl;
  
   getch();
   return 0;
}

Posted by: Dara | post date: 01-25-2013 | Subject: C++ Programming Language




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.