c - What is the Static Global Variable Purpose? -


i know variable declared static has scope in file in declared variable declared without static can accessed other files using extern declaration.

but true static "global" make variable retain last assigned value. static local purpose ?

#include <stdio.h>  void func() {  static int x = 0; // x initialized once across 3 calls of func()  printf("%d\n", x); // outputs value of x  x = x + 1; }  int main(int argc, char *argv[]) { func(); // prints 0 func(); // prints 1 func(); // prints 2 return 0; } 

the term "maintaining last value" causing confusion you. term "maintaining last value" used on context of function local variable vs function static variable. because variable declared within function got stored in stack, , on exiting function cleared stack used function leaves variable dead.

but creating function local variable static creating memory in ram(and not in stack), allows memory hold after exit of function. global variables , file static variables stored in ram thereby retaining value forever.

so, question variable stored in ram "maintain last value" irrespective of keyword static. static limits scope of usage, ie., if declared in file scope can used(accessed) within file, if declared in function scope scope limits within function alone.


Comments

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -