首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

内部static变量的一个倒子,为何说它用的好

2013-01-21 
内部static变量的一个倒子,为什么说它用的好?书上说:Consider the problem of writing a function month_n

内部static变量的一个倒子,为什么说它用的好?
书上说:
Consider the problem of writing a function month_name(n), which returns a pointer to a character string containing the name of the n?th month. This is an ideal application for an internal static array. month_name contains a private array of character strings, and returns a pointer to the proper one when called. This section shows how that array of names is initialized. 
The syntax is similar to previous initializations:


/* month_name: return name of n?th month */
char *month_name(int n)
{
    static char *name[] = {
        "Illegal month",
        "January", "February", "March",
        "April", "May", "June",
        "July", "August", "September",
        "October", "November", "December"
    };
    return (n < 1 || n > 12) ? name[0] : name[n];
}


书上说这里用的static变量用的很理想。为什么说这里static用的好呢?如果把static去掉,也没有多少影响吧?
[解决办法]
嗯,去掉也是正确的。
[解决办法]
嗯,可以去掉。加上static 给人感觉明白存在全局数据区。
[解决办法]

    static char *name[] = {
        "Illegal month",
        "January", "February", "March",
        "April", "May", "June",
        "July", "August", "September",
        "October", "November", "December"
    };
//去掉static,没有太多区别,不占函数的栈空间

[解决办法]
嗯是的 去掉也是正确的 这个static 用得没有价值 最多就是 
第二次开始调用函数的时候 不用重新构建这个数组罢了

热点排行