Scope of variables tells us where a variable can be used in the code. It helps keep things organized and avoids confusion.
Scope of variables in C++
/* Variable declared inside a function - local scope */ void example() { int x = 5; // x is local to example() } /* Variable declared outside functions - global scope */ int y = 10; // y is global int main() { // y can be used here return 0; }
Variables declared inside functions or blocks have local scope.
Variables declared outside all functions have global scope and can be used anywhere after declaration.
void func() { int a = 3; // 'a' is local to func // 'a' cannot be used outside func }
int b = 7; // global variable int main() { // 'b' can be used here return 0; }
int x = 1; // global void f() { int x = 2; // local to f, hides global x // inside f, 'x' is 2 } int main() { // here 'x' is 1 return 0; }
This program shows a global variable and a local variable inside a function. The local variable is only visible inside the function, but the global variable is visible everywhere.
#include <iostream> int globalVar = 100; // global variable void show() { int localVar = 50; // local variable std::cout << "Inside show(): localVar = " << localVar << "\n"; std::cout << "Inside show(): globalVar = " << globalVar << "\n"; } int main() { show(); // std::cout << localVar; // This would cause an error because localVar is not visible here std::cout << "Inside main(): globalVar = " << globalVar << "\n"; return 0; }
Local variables are created when the function/block starts and destroyed when it ends.
Global variables exist for the whole program run but use them carefully to avoid confusion.
Variables with the same name in different scopes do not interfere with each other.
Scope defines where a variable can be used in the program.
Local variables live inside functions or blocks only.
Global variables can be used anywhere after they are declared.