Static keyword questions with functions and data

I have a few questions about the static keyword in C ++ (and probably with other languages). What is the purpose of declaring a function as static?

void static foo(int aNumber) {
... }

What about a static inline function?

void static inline foo(int aNumber) {
... }

Is there any benefit to using a static keyword with a function, and also these benefits apply to class functions? I understand that some data types, such as structures and arrays, must be static when compiling with an older compiler, but does it make sense to use the new ANSI-C ++ compiler (for example, MS VC ++ 2008)? I know that using a static variable inside a loop saves time by storing data in memory rather than reallocating memory to each iteration of the loop, but what about when the variable is declared only once, for example, at the top of the header file or in the namespace?

+5
source share
2 answers

Depends on the context:

++, static .

++ , .
:

  • * , .
  • & , AND.

static:

, . ( ), .

:

a.cpp:

static void fn()
{
  cout<<"hello a!"<<endl;
}

b.cpp:

void fn();
void gn()
{
  fn();//causes linking error
}

, , , , . :

a.cpp:

namespace
{
  void fn() // will be static to a.cpp
  {
    cout<<"hello a!"<<endl;
  }
}

static:

( ), . , . . .

class C
{
public:
  static void fn()
  {
    y = 4;//<--- compiling error
    // can't access member variable within a static function.
  }

  int y;
}

, - , .

static:

, , . .

:

//Will print 0, then 1, then 2, ...
void persistentPrintX()
{
  static int x = 0;
  cout << x << endl;
  x++;
}

, , , . . , .

:

- ++, .

  • screen ( )
  • screen ( )

:

, , , , static - / vs --.

+15

## ++ irc ​​ irc.freenode.net, , nolyc. :

, static , . , , , . , .

, . . , static, , . , . , . , , .

, .

+3

All Articles