您的位置:首页 > 其它

精彩百例:静态变量和动态变量

2015-03-28 13:10 155 查看
/*
filename: sort of the memory for the variable
function: introduce the difference of the static variable and dynamic variable
*/
# include <stdio.h>

int sum_day(int month, int day);
int leap(int year);
int main(void)
{
int year, month, day;
int days;
/*input the data*/
printf("Please input the data(year,month,day): ");
scanf("%d %d %d", &year, &month, &day);
/*count which day of the year*/
days = sum_day(month, day);
/*if the year is leap year , the days need plus 1*/
if(leap(year) && month>=3)
days = days + 1;
printf("Today is the %d day of this year.\n ", days);

return 0;

/*define a static variable ,it does work start here */
static int day_tab[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
/*function:count the days of the year*/
int sum_day(int month, int day)
{
int i;
for(i=1; i<month; i++)
day = day + day_tab[i];

return day;
}
/*if the leap year*/
int leap(int year)
{
int leap;
leap = ((year%4 == 0) && (year%100 != 0));

return leap;
}
/*
静态存储变量是程序中整个运行时间都存在,
而动态存储变量是在调用函数时临时分配存储单元
在编译时分配存储空间的变量称为静态存储变量  static int a = 8;
静态变量无论是全局变量还是局部变量,定义和初始化都是在编译时进行的
作为局部比那两,调用函数结束时,静态存储变量不消失,并且保留原值
动态存储变量是指在程序运行期间分配固定的存储空间的方式
这些动态存储变量在函数调用时分配存储空间,当函数调用完之后,释放存储空间
auto int a, b, c;
auto是缺省的
所以说前面没有前缀的变量都是动态变量
*/

result:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c