你好,游客 登录 注册 搜索
背景:
阅读新闻

关于C中的static变量

[日期:2017-12-23] 来源:Linux社区  作者:gexin [字体: ]

C中的static变量

  • static变量分配在内存中的数据段,函数内部声明的static变量在函数调用结束时,依然保持在内存中,
#include<stdio.h>

int fun()
{
  static int count = 0;
  count++;
  return count;
}
  
int main()
{
  printf("%d ", fun());
  printf("%d ", fun());
  return 0;
}

/*******函数输出如下**********/

Process started >>>
1, 2 
<<< Process finished. (Exit code 0)
  • static变量如果没有初始化的话,会被隐式初始化为0
#include <stdio.h>
int main()
{
    static int x;
    printf("x = %d \n", x);
}


/**函数输出**/

x = 0
  • 静态变量只能被const类型的变量初始化,例如下面的函数会出错
#include<stdio.h>
int initializer(void)
{
    return 50;
}
  
int main()
{
    static int i = initializer();
    printf(" value of i = %d", i);
    getchar();
    return 0;
}

/********编译失败******/

Process started >>>
D:\static.c: In function 'main':
D:\static.c:9:20: error: initializer element is not constant
     static int i = initializer();
                    ^
<<< Process finished. (Exit code 1)

本文永久更新链接地址http://www.linuxidc.com/Linux/2017-12/149735.htm

linux
相关资讯       C static变量  C static 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款