c++全局变量_C全局变量

c++全局变量

In the C variables and types post I introduced how to work with variables.

C变量和类型文章中,我介绍了如何使用变量。

In this post I want to mention the difference between global and local variables.

在这篇文章中,我想提到全局变量和局部变量之间的区别。

A local variable is defined inside a function, and it’s only available inside that function.

局部变量是在函数内部定义的,并且仅在该函数内部可用。

Like this:

像这样:

#include <stdio.h>

int main(void) {
  char j = 0;
  j += 10;
  printf("%u", j); //10
}

j is not available anywhere outside the main function.

jmain功能之外的任何地方都不可用。

A global variable is defined outside of any function, like this:

全局变量是在任何函数之外定义的,如下所示:

#include <stdio.h>

char i = 0;

int main(void) {
  i += 10;
  printf("%u", i); //10
}

A global variable can be accessed by any function in the program. Access is not limited to reading the value: the variable can be updated by any function.

程序中的任何函数都可以访问全局变量。 访问不仅限于读取值:可以通过任何函数更新变量。

Due to this, global variables are one way we have of sharing the same data between functions.

因此,全局变量是我们在函数之间共享相同数据的一种方式。

The main difference with local variables is that the memory allocated for variables is freed once the function ends.

与局部变量的主要区别在于,函数结束后,将释放为变量分配的内存。

Global variables are only freed when the program ends.

仅在程序结束时才释放全局变量。

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

c++全局变量

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值