找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 357|回复: 1

Question1.10:Do all declarations for the same static function or variable have to inlcude...?

[复制链接]

210

主题

371

回帖

0

积分

管理员

积分
0
发表于 2013-7-13 21:47:15 | 显示全部楼层 |阅读模式

Q: Do all declarations for the same static function or variable have to include the storage class static?
A: The language in the Standard does not quite require this (what's most important is that the first declaration contain static), but the rules are rather intricate, and are slightly different for functions than for data objects. (There has also been a lot of historical variation in this area.) Therefore,
it's safest if static appears consistently in the definition and all declarations.

210

主题

371

回帖

0

积分

管理员

积分
0
 楼主| 发表于 2013-7-13 21:57:14 | 显示全部楼层
问题:同样的静态函数或者变量的声明都必须包含存储类别static吗?
回答:语言标准并没有必须要求这一点(最重要的是第一次声明必须包含static),但是规则对于函数却是比数据对象要复杂些。(在该区域里,也有很多历史方面的变化)因此,最为保险的方式就是让static一致地出现在定义和声明之中。
(注意:局部变量的静态变量只初始化一次,并且运算结果可以长期保留。)例子:
             f()
             {
                      static c=3;
                       c++;
                       return(c);
             }
          main()
         {

               int a=2,i;
               for(i=0;i<3;i++)
                       printf("%d",f());
           }

虽然在每一次我们进入函数f()的时候都有c=3,但是由于其为静态变量,只初始化一次,所以第二次进来的时候的值为上一次运算后保留的值4,所以这里最后的打印值为4,5,6。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

果子博客
扫码关注微信公众号

Archiver|手机版|小黑屋|风叶林

GMT+8, 2026-2-2 04:19 , Processed in 0.065270 second(s), 20 queries .

Powered by 风叶林

© 2001-2026 Discuz! Team.

快速回复 返回顶部 返回列表