Static usage in C/C++ — Why “static” uses?

Fırtına Hüseyin Göktaş
1 min readFeb 24, 2021

Scenario is that ;

— You would like to use variable with data type(e.g. unsigned int x) that act like a virus. Thanks to biology we know that viruses can revive in a live organism. Out of the live organism, viruses can’t live but if these viruses re-enter the live body than virus can revive again.

Static is exactly refer the same metaphore. Functions which staticly variables used in is like live body and staticly defined variable is like virus.

If the function calls again the variable revive. However out of this function the variable can’t achievable.

Let look at the example ;

void staticAdd(){
static unsigned int x = 10 ;
x++ ;
printf(“%d\n”, x);
}

void notStaticAdd(){

unsigned int x = 20 ;
x++ ;
printf(“%d \n” , x);
}

int main(int argc, char *argv[]) {

int a = 0 ;
for( a =0 ; a < 5 ; a++){
staticAdd();
}
for( a =0 ; a < 5 ; a++){
notStaticAdd();
}

return 0;
}

If you run the code you will get this result;

11

12

13

14

15

21

21

21

21

21

What about static functions?

Static functions uses for prevent the function collisions between two header file. If you would like to use same function name in two seperate header file , you can use static functions.

--

--