How to define and use static variable in a function in C

1 Answer

0 votes
#include <stdio.h>

void functionWithStatic(void);
void function(void);

int main(int argc, char **argv) 
{ 
    functionWithStatic();
    function();
    functionWithStatic();
    function();
    functionWithStatic();
    function();
    
    return(0);
}

void functionWithStatic(void)
{
   static int n = 0;
    
   n++;
   
   printf("static int n = %d\n", n);
}

void function(void)
{
   int x = 0;
    
   x++;
   
   printf("int x = %d\n", x);
}

/*
run:

static int n = 1
int x = 1
static int n = 2
int x = 1
static int n = 3
int x = 1

*/

 



answered Jun 12, 2015 by avibootz

Related questions

2 answers 175 views
1 answer 293 views
1 answer 224 views
1 answer 159 views
159 views asked Dec 27, 2020 by avibootz
1 answer 105 views
1 answer 193 views
1 answer 177 views
...