I have a confusion in the concepts of static integer.When i initialize a static integer in main function i.e
static int i;
Now the static integer is assigned a value 0.Now in the next step:
i++;
i becomes 1.
Now the program terminates. I want to know what program will produce on its’ next run. Also, what would happen if the entire program is closed? I understand that the first line is static int i; thus the next value when the function is next run should retain the value of i when it was previously run. If so, what is the advantage of making a variable static? Does the variable have a time limit or can it be stored forever? What would the value be if I ran the function again?
In C, “static” means that the variable has local scope within global storage.
The scope of variables in C is a block. In other words variables can be used inside the block they are declared. And normally they just keep their values until the block ends, being lost after that. Example:
This is true except for global variables that can be used all along the program.
The other exception is the static variable. It is only seen inside the block but keeps its value after the block is over.
This means that if you declare a static variable inside a function, it will maintain its value between function calls.
For example, the function below has a local variable. Local variables have scope of block (this means you can only access the variable ‘var’ inside the block {} it is declared, in the case below inside the function):
Once the variable is not static, every time you call the function it will print “Value is 1” because the variable is stored in the stack that is allocated on the function call and deallocated after the function returns.
If you change var to be static,
The first time you call the function var will be initialized as 0 and the function will show “Value is 1”. Nevertheless, at the second time, var will be already allocated and at a global area. It will not be initialized again and the function will display “Value is 2”.
This within the program execution.
Although a static variable is allocated as long as your program executes, it does not keep its value after your program finishes (the program will free all of its memory). The only way to keep any value for the next run is to store it at a non-volatile media like the disk.
Hope it helps.