Home » Learn C++ » Static Variables

Static Variables

Static Variables:

            Static variables arc special variables that are declared inside a function by using the keyword “static”. Like local variable, these can only be accessed in the function in which they are declared hut they remain in existence for the lifetime of the program. Another difference between local variables and static local variables is that the initialization in the static variables takes place only once when the function is called for the first time. A program example is given below that uses the static variables.

 

Program:

# include <iostream.h>
main ( )

{
int i;
int temp (int);
for (i = 1;  i<= 3;  i++)
{
cout << temp (i) << endl;
}
cout  << “Ok”;
}
int temp (int x)
{
static int co = 10;
Co = Co * x;
return (co) ;
}

 

The outputs of the above program will be as

10
20
60

 

Note: The static global variables can also be declared outside the main function but these are normally used in multiple-file programs.

Other Topics

comment closed

Get Adobe Flash playerPlugin by wpburn.com wordpress themes
Copyright © 2010 Information Village. All rights reserved.