DIGIT-ARC read-only archive · snapshot: July 23, 2026

static variables

7 posts · originally from https://geek.digit.in/community/threads/static-variables.166859/

Ashokkumar01cbe
Ashokkumar01cbe Original post #1
Nov 28, 2012 at 4:30 PM
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
Shah #2
Nov 28, 2012 at 4:46 PM
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
Nov 28, 2012 at 4:47 PM
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.
A
Jan 15, 2013 at 1:55 PM
static variables initializes only once. and scope is global
Shah
Shah #5
Jan 15, 2013 at 3:47 PM
^You are wrong. Scope has nothing to do with Static keyword. In this programs, The static variable has local scope.
vickybat
Jan 16, 2013 at 1:34 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
Shah #7
Jan 16, 2013 at 9:16 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.

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