Home >Backend Development >C#.Net Tutorial >What is the scope of a variable
The scope of a variable refers to the range of variable validity, which is the code range that user-defined variables can use; it is closely related to the location of the variable definition.
Scope
describes variables from the perspective of space. According to different scopes, variables can be divided into local variables and global variables.
1. Local variables
Local variables are variables defined inside a function (or code block), also called internal variables, local A variable can only be accessed and used within the function (or code block) in which it is defined, and cannot be used by other functions.
The scope of a local variable is limited to the code block in which it is described: from the beginning of the description to the end of the code block. It is illegal to use such a variable after leaving the function.
Example:
int f1(int a) { int b,c; …… }a,b,c作用域 int f2(int x) { int y,z; }x,y,z作用域 main() { int m,n; }
Explanation: a is a formal parameter, b, c are general variables; within the scope of f1, a, b, c are valid, or a, b, c variables The scope is limited to f1. In the same way, the scope of x, y, z is limited to f2; the scope of m, n is limited to the main function.
Note that variables with the same name are not allowed in the same scope.
2. Global variables
Global variables are variables declared in the global environment. Its scope is from the definition point until the program End of file; it occupies storage units throughout the entire run of the program.
Global variables change the value of global variables in a function and can be shared by other functions; it is equivalent to transferring data between functions.
Example:
int a,b; void f1() { …… } float x,y; int fz() { …… } main() { …… }
Explanation: a, b, x, y are all external variables defined outside the function and are all global variables. However, x and y are defined after function f1, and there is no description of x and y in f1, so they are invalid in f1. a, b are defined at the beginning of the source program, so they can be used without explanation in f1, f2 and main.
Code example:
Input the length, width and height l,w,h of the cube. Find the volume and the areas of the three faces x*y, x*z, y*z.
#include <stdio.h> int s1,s2,s3;//全局变量 int vs( int a,int b,int c) { int v;//局部变量 v=a*b*c; s1=a*b; s2=b*c; s3=a*c; return v; } main() { int v,l,w,h;//局部变量 printf("\n分别输入长度l、宽度w和高度h:\n"); scanf("%d%d%d",&l,&w,&h); v=vs(l,w,h); printf("面积1为:%d,面积2为:%d,面积3为:%d\n",s1,s2,s3); printf("体积为:%d",v); }
Output:
The above is the detailed content of What is the scope of a variable. For more information, please follow other related articles on the PHP Chinese website!