一般来说,范围是指可以处理某件事情的程度。在编程中,变量的范围也被定义为程序代码的范围,在此范围内可以访问、声明或使用变量。变量作用域主要有两种类型:
- 局部变量
- 全局变量
现在让我们更详细地了解每个范围:
局部变量
函数或块中定义的变量称为这些函数的局部变量。
- “{”和“}”之间的任何东西都被称为在一个区块内。
- 局部变量不存在于声明它们的块之外,即 不能 可在该街区外访问或使用。
- 声明局部变量 :局部变量在块内声明。
C++
// CPP program to illustrate // usage of local variables #include<iostream> using namespace std; void func() { // this variable is local to the // function func() and cannot be // accessed outside this function int age=18; } int main() { cout<< "Age is: " <<age; return 0; } |
输出:
Error: age was not declared in this scope
上面的程序显示一个错误,说明“年龄未在此范围内声明”。变量age是在函数func()中声明的,因此它是该函数的局部变量,对于该函数之外的程序部分不可见。
修正程序 :要更正上述错误,我们必须仅显示函数func()中变量age的值。如下程序所示:
C++
// CPP program to illustrate // usage of local variables #include<iostream> using namespace std; void func() { // this variable is local to the // function func() and cannot be // accessed outside this function int age=18; cout<<age; } int main() { cout<< "Age is: " ; func(); return 0; } |
输出:
Age is: 18
全局变量
顾名思义,全局变量可以从程序的任何部分访问。
- 它们在程序的整个生命周期内都是可用的。
- 它们在所有函数或块之外的程序顶部声明。
- 声明全局变量 :全局变量通常在程序顶部的所有函数和块之外声明。它们可以从程序的任何部分访问。
C++
// CPP program to illustrate // usage of global variables #include<iostream> using namespace std; // global variable int global = 5; // global variable accessed from // within a function void display() { cout<<global<<endl; } // main function int main() { display(); // changing value of global // variable from main function global = 10; display(); } |
输出:
510
在程序中,变量“global”在所有函数之外的程序顶部声明,因此它是一个全局变量,可以从程序中的任何位置访问或更新。
如果函数中存在与全局变量同名的局部变量,该怎么办?
让我们再次重复这个问题。问题是:如果函数中有一个与全局变量同名的变量,并且该函数试图访问具有该名称的变量,那么哪个变量将优先?局部变量还是全局变量?看下面的程序来理解这个问题:
C++
// CPP program to illustrate // scope of local variables // and global variables together #include<iostream> using namespace std; // global variable int global = 5; // main function int main() { // local variable with same // name as that of global variable int global = 2; cout << global << endl; } |
看看上面的程序。顶部声明的变量“global”是全局变量,存储值5,其中在main函数中声明的变量是局部变量,存储值2。所以,问题是当名为“global”的变量中存储的值从主函数打印出来时,输出是什么?2还是5?
- 通常,当定义两个同名变量时,编译器会产生编译时错误。但是如果变量定义在不同的范围内,那么编译器允许它。
- 每当有一个局部变量定义为与全局变量同名时 编译器将优先于局部变量
当存在同名的局部变量时,如何访问全局变量?
如果我们想做与上述任务相反的事情呢。如果我们想在有同名的局部变量时访问全局变量呢? 为了解决这个问题,我们需要使用 范围解析运算符 .下面的程序解释了如何在范围解析操作员的帮助下执行此操作。
C++
// C++ program to show that we can access a global // variable using scope resolution operator :: when // there is a local variable with same name #include<iostream> using namespace std; // Global x int x = 0; int main() { // Local x int x = 10; cout << "Value of global x is " << ::x; cout<< "Value of local x is " << x; return 0; } |
输出:
Value of global x is 0Value of local x is 10
本文由 严酷的阿加瓦尔 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。