主题:[讨论]关于多文件中static变量的生存期
最近在看 《c primer plus》,里面有个关于多文件中static变量的使用问题,求高手指点
程序清单 12.5 parta,c文件
#include <stdio.h>
void report_count ();
void accumulate (int k);
int count = 0;
int main (void)
{
int value;
register int i;
printf ("Enter a positive integer (0 to quit): ");
while (scanf ("%d", &value) == 1 && value > 0)
{
++count;
for (i = value; i >= 0; i--)
accumulate (i);
printf ("Enter a positive integer (0 to quit): ");
}
report_count ();
return 0;
}
void report_count ()
{
printf ("Loop executed %d times\n", count);
}
程序清单 12.6 partb,c文件
#include <stdio.h>
extern int count;
static int total = 0;
void accumulate (int k);
void accumulate (int k)
{
static int subtotal = 0;
if (k <= 0)
{
printf ("loop cycle: %d\n", count);
printf ("subtotal: %d; total: %d\n", subtotal, total);
subtotal = 0;
}
else
{
subtotal += k;
total += k;
}
}
运行示例:
Enter a positive integer (0 to quit): 5
loop cycle: 1
subtotal: 15; total: 15
Enter a positive integer (0 to quit): 10
loop cycle: 2
subtotal: 55; total: 70
Enter a positive integer (0 to quit): 2
loop cycle: 3
subtotal: 3; total: 73
Enter a positive integer (0 to quit): 0
Loop executed 3 times
根据书上所说及自己的理解,partb中的两个static变量都是存在静态存储区,虽然作用域不一样,但生存期是一样的,都应该生存到文件执行结束,这样两个变量的值应该是一样的,为什么运行结果不一样呢,求高手指点
程序清单 12.5 parta,c文件
#include <stdio.h>
void report_count ();
void accumulate (int k);
int count = 0;
int main (void)
{
int value;
register int i;
printf ("Enter a positive integer (0 to quit): ");
while (scanf ("%d", &value) == 1 && value > 0)
{
++count;
for (i = value; i >= 0; i--)
accumulate (i);
printf ("Enter a positive integer (0 to quit): ");
}
report_count ();
return 0;
}
void report_count ()
{
printf ("Loop executed %d times\n", count);
}
程序清单 12.6 partb,c文件
#include <stdio.h>
extern int count;
static int total = 0;
void accumulate (int k);
void accumulate (int k)
{
static int subtotal = 0;
if (k <= 0)
{
printf ("loop cycle: %d\n", count);
printf ("subtotal: %d; total: %d\n", subtotal, total);
subtotal = 0;
}
else
{
subtotal += k;
total += k;
}
}
运行示例:
Enter a positive integer (0 to quit): 5
loop cycle: 1
subtotal: 15; total: 15
Enter a positive integer (0 to quit): 10
loop cycle: 2
subtotal: 55; total: 70
Enter a positive integer (0 to quit): 2
loop cycle: 3
subtotal: 3; total: 73
Enter a positive integer (0 to quit): 0
Loop executed 3 times
根据书上所说及自己的理解,partb中的两个static变量都是存在静态存储区,虽然作用域不一样,但生存期是一样的,都应该生存到文件执行结束,这样两个变量的值应该是一样的,为什么运行结果不一样呢,求高手指点