⋮
In C++, the area of the program where a variable is accessible is referred to as its scope. Depending on where and how they are declared, variables in C++ can have one of multiple scopes.
1. Local Scope
A variable that is declared inside a block (contained by {}) is only available within that block and has local scope.
example:
void example() {
int x = 10; // Local scope
std::cout << x; // Accessible here
}
// std::cout << x; // Error: x is not accessible here
2. Global Scope:
A global variable is one that is defined outside of all functions and classes. From the program's declaration point on, it is available throughout.
Example:
int globalVar = 20; // Global scope
void example() {
std::cout << globalVar; // Accessible here
}
3. Function Scope
Function parameters and any variables declared inside a function are only available within that function.
Example:
void example(int param) { // param has function scope
int x = 10; // x has function scope
std::cout << param + x;
}
4. Class Scope (Member Variables):
Declared variables inside a class are members of that class and can be accessed directly within member functions or through class objects.
Example:
class MyClass {
int x; // Class scope (instance variable)
static int y; // Class scope (static variable)
public:
void setX(int val) { x = val; }
};
5. Namespace Scope:
Declared variables can be accessed within a namespace or by explicitly defining the namespace (or by using a using directive).
Example:
namespace MyNamespace {
int x = 5;
}
int main() {
std::cout << MyNamespace::x; // Access with namespace
}
6. File Scope (Static Variables):
File scope refers to the fact that a global variable declared with the static keyword can only be accessed within the file in which it is declared.
Example:
static int fileScopeVar = 10; // Accessible only in this file
7. Block Scope:
A variable that is declared inside a block (for example, inside conditionals or loops) can only be accessed inside that block.
Example:
if (true) {
int y = 10; // Block scope
}
// std::cout << y; // Error: y is not accessible here
Comments