Using static variables inside functions

I have been writing C code for many years, but recently I came up with a function that I have never used: a static variable inside a function. So I was wondering how you used this feature, and it was the right design decision.

eg.

int count(){
    static int n;
    n = n + 1;
    return n;
}

is a constructive solution to BAD. What for? because later on you may want to decrease the counter, which will include changing the parameters of the function, changing the entire calling code, ...

Hope this is clear enough, thanks!

+3
source share
4 answers
void first_call()
{
   static int n = 0;

   if(!n) {
     /* do stuff here only on first call */
     n++;
   }

   /* other stuff here */
}
+4
source

. . ( , , ), , , , , . . , .

+2

.

, # 1 ( ) , :

/* on thread #1 */
static bool run_thread = true;
// then initialize the worker thread

# 2, , # 1 :

/* thread #2 */
while (run_thread)
{
  // work until thread #1 stops me
}
0

, static , . POSIX:

static pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_lock(&mut);
/* critical code comes here */
pthread_mutex_unlock(&mut);

auto.

POSIX static , .

0

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


All Articles