use of static in variable and class

What does the meaning of static when we use this in front of variable or class
like

static int a =4;

static class abc;

Please brief the use of static with some example.

In a function, local variables are destroyed as soon as you exit. Static variables are... well... static in that they continue existing and will continue holding a value you set. Plus, they are only initialized once.

1
2
3
4
5
int funky(int n){
   static int counter(-n); //Initialization only happens once. counter will not be "reset"
   counter += n; //This will add n to the current value of counter
   return counter;
}


So, if you had:
1
2
3
4
   funky(3); //counter == 0
   funky(4); //counter == 4
   funky(20); //counter == 24
//and so on... 


Same goes with objects.
AFAIK, in C++, there are only static variables and static functions, but no static classes.

Static Variables:

1. When declared inside a function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void myCount( ) {

  static int counter = 0;
  int nonStaticCounter = 0;
  counter++;
  nonStaticCounter++;

  // This gives the number of times the function has been called till now.
  std::cout << "static counter = " << counter << std::endl;

  // This outputs 1 every time.
  std::cout << "non-static counter = " << nonStaticCounter << std::endl;

  return;
}

The non-static local variables are destroyed once the function ends and a new one is created whenever the function is again called. A static variable remains even after the function ends and it retains it value for subsequent function calls. It is intitialized the first time the function is called.

2. When declared as a member variable in a class, then they do not need object instantiation to get access to. They can be directly accessed through the class name itself, MyCLass::myStaticMember.

Static member functions
Similar to static member variables of a class.
Last edited on
@abhishekm71

AFAIK, in C++, there are only static variables and static functions, but no static classes.


Variable can have a class type. So you can declare objects of a class type as static. Moreover anonymous unions shall be specified with storage class specifier static. Also object of a class type can be members of another class and also be declared with static specifier.
I think he meant there is no static class blah {};. Or is there? Even then, you might as well use a namespace instead of a "static class".
@vlad
ok thanks,

I understand your 1st and 3rd statement. Can you please elaborate on the second one? What are anonymous unions?
abhishekm71,

Static is playing the role like global variable

what is the difference between static and global variables.

and please brief the use of static in functions.
Static variable is not like global variable.

A global variable can be "accessed" from anywhere in the program whereas a local static variable can be "accessed" only within the function.
Last edited on
What are static functions?
Following link provides a lot of information:
http://stackoverflow.com/questions/558122/what-is-a-static-function
@abhishekm71

@vlad
ok thanks,

I understand your 1st and 3rd statement. Can you please elaborate on the second one? What are anonymous unions?


From the C++ Standard

5 A union of the form union { member-specification } ;
is called an anonymous union; it defines an unnamed object of unnamed type. The member-specification of an anonymous union shall only define non-static data members. [ Note: Nested types and functions cannot be declared within an anonymous union. —end note ] The names of the members of an anonymous union shall be distinct from the names of any other entity in the scope in which the anonymous union is declared. For the purpose of name lookup, after the anonymous union definition, the members of the anonymous union are considered to have been defined in the scope in which the anonymous union is declared. [ Example:
void f() {
union { int a; const char* p; };
a = 1;
p = "Jennifer";
}
Here a and p are used like ordinary (nonmember) variables, but since they are union members they have the same address. —end example ]
In addition, when static is applied to a variable or function at file or namespace scope, the variable (or function) has internal linkage. i.e. it can only be seen and used within a single cpp file (see PS for a bit more...)

Variables (and functions) need to have external linkage to be seen in other .cpp files, which is the point of the extern key word.

To complicate matters a bit, in C++ constants have internal linkage by default, but not in C.

The use of the const in the following code is valid C++ but not C

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// main.cpp

#include <iostream>
#include "example.h"

using namespace std;

int main()
{
    cout<< "PI = " << PI << endl;
    cout<< "the_answer = " << the_answer << endl;

    return 0;
}


1
2
3
4
5
6
7
8
9
10
#ifndef Included_Example_h
#define Included_Example_h

// example.h

const double PI = 3.1415927; // has internal linkage in C++

extern double calc_area_of_circle(double radius);

#endif // Included_Example_h 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
// example.cpp

#include "example.h"

// sqr can only be seen in example.cpp
static double sqr(double value)
{
    return (value * value);
}

double calc_area_of_circle(double radius)
{
    return PI * sqr(radius);
}


If the header will be used with C code, the constant should be marked as static. Otherwise the program will fail to link due to the multiple definition of PI (in this case.)

Note this is the one valid (standard) use of static in header files (aside from the use in class definitions); when used with constants of small size, it makes it easier for the compiler to inline the value (i.e. the generated object code will not have a constant variable; it will just use the value as if you had typed in a literal.)

Andy

PS More formally, the the use of static with a variable of function at file or namespace scope limites the use of the the variable of function to the current translation unit. A translation unit is the file that's created by the preprocessing step, so it's the original .cpp plus the contents of all the headers it includes after all the #define-d macros have been expanded, the #ifdef, etc. applied, etc.

This translation unit (i.e. the output of the preprocessor) is what is fed to "the translator", i.e. the actual compiler.

Translation unit (programming)
http://en.wikipedia.org/wiki/Translation_unit_%28programming%29

Last edited on
Topic archived. No new replies allowed.