c语言全局变量和局部变量_C语言的范围是什么? 写局部变量和全局变量/范围之间的差异...

c语言全局变量和局部变量

The scope is a particular region in the program, where variables, constants have their existence and can be accessed. In other words, we can say that “the area where a variables, constants are accessible known as Scope of a variable.

范围是程序中的特定区域,变量,常量在其中存在并且可以访问。 换句话说,我们可以说“变量,常量可访问的区域称为变量的范围”

Scope defines the following things:

范围定义以下内容:

  • Accessibility of a variable, constant

    变量,常量的可访问性

  • Lifetime of a variable, constant

    变量的寿命,常数

  • Memory segment where the memory bytes should be reserved for the variables, constants

    应该为变量,常量保留内存字节的内存段

  • Deallocation time of the reserved memory bytes

    保留内存字节的重新分配时间

Example code:

示例代码:

#include <stdio.h>

/*global scope*/
int a = 10;

void fun(void)
{
	/*local scope to this function only*/
	int c=30;
	printf("a =%d, c=%d\n",a,c);
}

int main()
{
	/*local scope*/	
	int b=20;
	printf("a=%d, b=%d\n",a,b);
	fun();
	
	return 0;
}

Output

输出量

    a=10, b=20
    a =10, c=30

In the above code,

在上面的代码中,

  • a is global variable and it is accessible in any scope of the program, we have used it in main() as well as fun() function.

    a是全局变量,可以在程序的任何范围内访问,我们已经在main()和fun()函数中使用了它。

  • b is a local variable of main() and it is accessible only in main() function.

    b是main()的局部变量,只能在main()函数中访问。

  • c is a local variable of fun() and it is accessible only in fun() function.

    c是fun()的局部变量,只能在fun()函数中访问。

全球范围与本地范围之间的差异 (Difference between global and local scope)

Local scopeGlobal scope
The variables which are declared in local scope (scope of any function) are known as local variables to that function.The variables which are declared in Global scope (outside of the main) are known as Global variables to the program.
These variables can be accessible within the same block only in which they are declared. These variables can be accessible within the complete program (in all functions).
Memory is released when program’s execution comes out from the scope.Memory is released when program’s execution finishes.
Variables declared inside the local scope are stored in stack segment, unless specified.Variables declared inside the Global scope are stored in data segment.
当地范围 全球范围
在局部作用域(任何函数的作用域)中声明的变量称为该函数的局部变量。 在全局范围(在主范围之外)中声明的变量在程序中称为全局变量。
这些变量只能在声明它们的同一块中访问。 这些变量可以在整个程序中(在所有功能中)访问。
当程序的执行从范围中出来时,将释放内存。 程序执行完成后释放内存。
除非指定,否则在局部范围内声明的变量将存储在堆栈段中。 在全局范围内声明的变量存储在数据段中。

翻译自: https://www.includehelp.com/c/local-and-global-variables-scope.aspx

c语言全局变量和局部变量

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值