Skip to content

Instantly share code, notes, and snippets.

@kougazhang
Last active January 17, 2022 07:11
Show Gist options
  • Save kougazhang/d0e0b8a295555db2418b3f36c063924d to your computer and use it in GitHub Desktop.
Save kougazhang/d0e0b8a295555db2418b3f36c063924d to your computer and use it in GitHub Desktop.
#c++
#include <iostream>
// 函数声明
void func(void);
static int count = 10; /* 全局变量 */
int main()
{
while(count--)
{
func();
}
return 0;
}
// 函数定义
void func( void )
{
// 结合输出可发现,i 第一次初始化为 5,
// 后续 func 再次被调用时,i 不会被再次初始化为 5
// 所以输出中可以发现,i 打印出来的值在不断被累加
static int i = 5; // 局部静态变量
i++;
std::cout << "变量 i 为 " << i ;
std::cout << " , 变量 count 为 " << count << std::endl;
}
@kougazhang
Copy link
Author

变量 i 为 6 , 变量 count 为 9
变量 i 为 7 , 变量 count 为 8
变量 i 为 8 , 变量 count 为 7
变量 i 为 9 , 变量 count 为 6
变量 i 为 10 , 变量 count 为 5
变量 i 为 11 , 变量 count 为 4
变量 i 为 12 , 变量 count 为 3
变量 i 为 13 , 变量 count 为 2
变量 i 为 14 , 变量 count 为 1
变量 i 为 15 , 变量 count 为 0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment