Robotics C++ Physics II AP Physics B Electronics Java Astronomy Other Courses Summer Session  

static Variables

Description

Variables declared in a function are local variables.

They are known only to the function and lose their value after the function is exited.

A way to force the function to remember the last value of the variable is to declare it static, along with the data type.

The variable is then initialized to zero for that point only.

If the variable is incremented each time the function is entered, then a record can be kept of the number of times the function is called.

Example

// swap.cpp : Defines the entry point for the console application.

#include "stdafx.h"

#include<iostream>

using namespace std;

int sample();

int main()

{

      for(int i = 1; i<10;i++)

      {

         sample();

      }

      int total = sample();

      cout<<"The sample function was called "<<total<<" times"<<endl;

      return 0;

}

int sample()

{

      //function will now remember the last call; initialized to 0 1st time only

      static int number;           

      number = number++;

      return number;

}