main() { static int i;
printf("%d\n",i); // should I see see 0 or 5 ???
for (i=5;i<=15;i++) {...} // What's the meaning of static
variable in
// for's init section???
}
Note that uncompilable code is not a good idea. Let's start with this
version of your code
[1]
#include <stdio.h>
int main(void)
{
static int i;
printf("%d\n", i);
for (i = 5; i <= 15; i++)
printf("%d%c", i, (i == 15) ? '\n' : ' ');
return 0;
}
The difference between this and
[2]
#include <stdio.h>
int main(void)
{
int i;
printf("%d\n", i);
for (i = 5; i <= 15; i++)
printf("%d%c", i, (i == 15) ? '\n' : ' ');
return 0;
}
is that in [1] i is initialized (to 0) and in [2] it is used
uninitialized in the first printf statement. Static variables are
initialized by default (although initialization by default is probably a
poor programming practice). So [1] has well defined output:
0
5 6 7 8 9 10 11 12 13 14 15
while [2], using an uninitialized variable, does not.
The example here does not really show why a static variable might be
used. Variables within a block without the 'static' are 'auto'
(automatic) variables. Each entry to the block has a logically new
variable to work with. Static variables are an implementation of what
in Algol were called 'own' variables; they persist from one use of the
block to the next. Here's an example that I hope will show the difference:
#include <stdio.h>
void auto_i(void)
{
int i = 0;
printf("In 'auto_i', i = %d\n", i);
i++;
}
void static_i(void)
{
static int i = 0;
printf("In 'static_i', i = %d\n", i);
i++;
}
int main(void)
{
int j;
for (j = 0; j < 4; j++) {
auto_i();
static_i();
}
return 0;
}
[output]
In 'auto_i', i = 0
In 'static_i', i = 0
In 'auto_i', i = 0
In 'static_i', i = 1
In 'auto_i', i = 0
In 'static_i', i = 2
In 'auto_i', i = 0
In 'static_i', i = 3