Static Variables

can anyone explain when to use static variables and why?

+3
source share
4 answers

In C:

there are 2 different uses of the keyword static
  • Static function declarations
  • Static ads out of scope

(MOST) EVIL: static variables in a function

A static variable in a function is used as the state of "memory".

Basically, your variable is initialized to the default value only the first time you call it, and then saves its previous value in all future calls.

, , , : .

, EVIL/ BAD.

:

#include <stdio.h>


void  ping() {
  static int counter = 0;

  return (++counter);
}

int   main(int ac, char **av) {
  print("%d\n", ping()); // outputs 1
  print("%d\n", ping()); // outputs 2
  return (0);
}

:

1
2

() :

static (, , ).

, , , . . , /var "" , , , , " ".

, .

, GOOD.

:

example.h

#ifndef __EXAMPLE_H__
# define __EXAMPLE_H__

void  function_in_other_file(void);

#endif

file1.c

#include <stdio.h>

#include "example.h"

static void  test(void);


void test(void) {
  printf("file1.c: test()\n");
}

int   main(int ac, char **av) {
  test();  // calls the test function declared above (prints "file1.c: test()")
  function_in_other_file();
  return (0);
}

file2.c

#include <stdio.h>

#include "example.h"

static void  test(void); // that a different test!!


void test(void) {
  printf("file2.c: test()\n");
}

void   function_in_other_file(void) {
  test();  // prints file2.c: test()
  return (0);
}

:

file1.c: test()
file2.c: test()

PS: , : , , , , " " ( ) C. .

+8

C static :

1) , static

2), , static ( "" ),

+2

http://en.wikipedia.org/wiki/Static_variable

C , , ( extern ..)

static , , .

, - .

+2

, .

, ?

, . 10.

  for(int z=0; z<10; z++)
  {
    static int number_of_times = 0;
    number_of_times++;
  }

- .

, -

- -

, , , . . ( - )

0

Source: https://habr.com/ru/post/1778147/


All Articles