static variables

Ashokkumar01cbe

Broken In
hi frnds
void staticno();
void main()
{
staticno();
staticno();
staticno();

}
void staticno()
{
static int c=0;

printf("\n%d",c++);
}
the output i got is 0
1
2
and for this program second program
void staticno();
void main()
{
staticno();
staticno();
staticno();

}
void staticno()
{
static int c;
c=0;
printf("\n%d",c++);
}
i got the output as 0
0
0. the above two programs are almost same but i got different kind of outputs please explain me..
 

Shah

Cyborg Agent
In the first program, the variable 'c' is initialized to 0 for the first time only, when the variable is created. But, in the second one, the line "c = 0" sets the value of c to 0, each time when the function is called.
 

krishnandu.sarkar

Simply a DIGITian
Staff member
In first program you wrote...

static int c = 0;

^^This line means, declare (define) a static int variable named c and initialize it to 0.

Now first time when the function is called it does that, but from next time it ignores that line as compiler already have declared and initialized that variable. So the program is working as it should.

On 2nd Program you wrote...

static int c;
c = 0;

Note : Whenever a static variable is declared it's by default initialized with 0 and not with garbage values as in case of normal variables.

So every-time the function is called, you are explicitly setting c to 0 by saying c=0;

So you are not getting the desired result.

Hope you understand what's wrong.... The thing is on 2nd line.
 

Shah

Cyborg Agent
^You are wrong. Scope has nothing to do with Static keyword. In this programs, The static variable has local scope.
 

vickybat

I am the night...I am...
In the first code, static variable c was initialized to 0. Now static variables keep the same copy for local scope or instance. For each increment of c, the variable stores the incremented value over and over. Had it been a normal variable initialized to 0, you would get output as 0,0,0 because it won't store newer copies and get initialized over and over again.

In 2nd code, you explicitly set c to 0 each time after initialization.
 

Shah

Cyborg Agent
In the first code, static variable c was initialized to 0. Now static variables keep the same copy for local scope or instance. For each increment of c, the variable stores the incremented value over and over. Had it been a normal variable initialized to 0, you would get output as 0,0,0 because it won't store newer copies and get initialized over and over again.

In 2nd code, you explicitly set c to 0 each time after initialization.

The OP's query has been already answered, few months back.
 
Top Bottom