C++
Variable Scope (Local vs Global)
Variable scope is a concept in programming that determines where a variable can be accessed from in a program. There are two types of variable scope in C++: local and global.
- Local variables: Local variables are declared within a function or block of code. They can only be accessed from within the function or block of code in which they are declared.
- Global variables: Global variables are declared outside of any function or block of code. They can be accessed from anywhere in the program.
Example of local variable scope:
int main() {
int local_variable = 10;
// local_variable can only be accessed from within this function.
std::cout << local_variable << std::endl;
// This code will cause an error because local_variable is not accessible here.
std::cout << global_variable << std::endl;
return 0;
}
Example of global variable scope:
int global_variable = 20;
int main() {
// global_variable can be accessed from anywhere in the program.
std::cout << global_variable << std::endl;
// This code is also valid.
int local_variable = global_variable;
return 0;
}
It is important to be aware of variable scope when writing C++ code. Otherwise, you may accidentally access a variable that is not defined or that you are not supposed to access.
Here are some general rules for variable scope in C++:
- Local variables are scoped to the function or block of code in which they are declared.
- Global variables are scoped to the entire program.
- Variables declared in a function can shadow variables declared in the global scope.
- Variables declared in a block of code can shadow variables declared in the function scope.
By understanding variable scope, you can write more efficient and reliable C++ code.