#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);
}``` Aren't static variables supposed to hold value? Then why does it output `` n 4 2 n 6 2 n 2 0 ``?
#Static Variable
6 messages · Page 1 of 1 (latest)
When your question is answered use !solved to mark the question as resolved.
Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.
you have 3 distinct as in this program
- First one is the file-scoped (global)
a(declared at the top after stdio header inclusion) - Second one is the block-scoped (local; visible only in the
mainfunction's curlies)a, declared inmain - Third one is again block-scoped (local; this time visible only in
prtFunfunction's curlies)a, declared inprtFun
Above remarks identify the scope of the variables. There is an (independent) concept of storage duration -- basically what will be the lifetime of a given variable, when it comes to life and when it dies out.
In your case, all of the three as have static storage duration, i.e., they persist so long as the program executes from beginning to end. First one is static by virtue of being a global variable, that a will start living when program begins, and will be inaccessible when the entire program finishes. Second and third ones are static because you specifically asked for it by the static keyword there. These latter two persist across calls too (initalize only once) but the difference from the first one is that they are locally persistent given the identification of scope we have above. So, prtFuns a is only visible in prtFun and is totally different than main's a which is only visible in main. Lastly note that by using the same name a in main and prtFun to declare those variables, you are shadowing the global a, so it's not the one used in neither of the functions. But b in main refers to the global one (b in prtFun refers to the local b you declared to shadow the global)
In short, yes static variables are supposed to "hold value" and they do indeed; but you have different (albeit with the same name) static variables in each function.