c# 静态变量与非静态变量_C中的静态变量

c# 静态变量与非静态变量

Inside a function, you can initialize a static variable using the static keyword.

在函数内部,可以使用static关键字初始化静态变量

I said “inside a function”, because global variables are static by default, so there’s no need to add the keyword.

我说“在函数内部”是因为默认情况下全局变量是静态的,因此无需添加关键字。

What’s a static variable? A static variable is initialized to 0 if no initial value is specified, and it retains the value across function calls.

什么是静态变量? 如果未指定初始值,则静态变量将初始化为0,并在函数调用期间保留该值。

Consider this function:

考虑以下功能:

int incrementAge() {
  int age = 0;
  age++;
  return age;
}

If we call incrementAge() once, we’ll get 1 as the return value. If we call it more than once, we’ll always get 1 back, because age is a local variable and it’s re-initialized to 0 on every single function call.

如果我们调用一次incrementAge() ,我们将获得1作为返回值。 如果我们多次调用它,我们总是会得到1,因为age是一个局部变量,并且在每次调用函数时都会将其重新初始化为0

If we change the function to:

如果将函数更改为:

int incrementAge() {
  static int age = 0;
  age++;
  return age;
}

Now every time we call this function, we’ll get an incremented value:

现在,每次调用此函数时,我们将获得一个递增的值:

printf("%d\n", incrementAge());
printf("%d\n", incrementAge());
printf("%d\n", incrementAge());

will give us

会给我们

1
2
3

We can also omit initializing age to 0 in static int age = 0;, and just write static int age; because static variables are automatically set to 0 when created.

我们也可以省略初始化age在0 static int age = 0; ,并只写static int age; 因为静态变量在创建时会自动设置为0。

We can also have static arrays. In this case, each single item in the array is initialized to 0:

我们也可以有静态数组。 在这种情况下,数组中的每个项目都初始化为0:

int incrementAge() {
  static int ages[3];
  ages[0]++;
  return ages[0];
}

翻译自: https://flaviocopes.com/c-static-variables/

c# 静态变量与非静态变量

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值