I'm learning C and came across this program.
#include <stdio.h>
int a, b, c = 0;
void prtFun (void);
int main ()
{
static int a = 1; /* line 1 */
prtFun();
a += 1;
prtFun();
printf ( "n %d %d " , a, b) ;
}
void prtFun (void)
{
static int a = 2; /* line 2 */
int b = 1;
a += ++b;
printf (" n %d %d " , a, b);
}
The output is as follows:
4 2
6 2
2 0
It gives the following explanation
"‘a’ and ‘b’ are global variable. prtFun() also has ‘a’ and ‘b’ as local variables. The local variables hide the globals (See Scope rules in C). When prtFun() is called first time, the local ‘b’ becomes 2 and local ‘a’ becomes 4. When prtFun() is called second time, same instance of local static ‘a’ is used and a new instance of ‘b’ is created because ‘a’ is static and ‘b’ is non-static. So ‘b’ becomes 2 again and ‘a’ becomes 6. main() also has its own local static variable named ‘a’ that hides the global ‘a’ in main. The printf() statement in main() accesses the local ‘a’ and prints its value. The same printf() statement accesses the global ‘b’ as there is no local variable named ‘b’ in main. Also, the defaut value of static and global int variables is 0. That is why the printf statement in main() prints 0 as value of b."
I was under the impression that static variables in C are declared only once and have a global scope and also that all global variables were implicitly static. So how is it correct that you can redeclare these static variables in different scopes given the global scope of either the implicit declaration of the global variables or the explicit declaration in main? If there is only one place in memory for a static variable and it has a global scope how are there block specific static variables in this program with the same name?
Thanks
static int avariables inmainand inprtFunare two different variables which happen to be homonymousint a, b, c = 0;you only explicitly initializecto zero, but not the others. However, C is specified to "zero initialize" all global (but otherwise uninitialized) variables, so they all become zero anyway.staticis a storage class specifier, which define the life of object, but doesn't influence nor change, with very few exceptions, the standard scoping rules for variables, local or global.staticis storage duration. The two concepts are orthogonal.staticvariable's lifetime is the entire program, it doesn't "become" something when you "first call the function". It certainly does not become something when you call it agfain.