In C++ the scope of a variable refers to the part of the program where the variable is accessible. Variables can have different scopes depending on where they are declared.
Local Variables
Local variables are declared inside a function and are only accessible within that function. Their lifetime begins when the function is called and ends when the function returns.
#include <iostream>
void myFunction() {
int number = 10; // Local variable, only exists in this function
std::cout << number << std::endl; // ✔️ You can use it here
}
int main() {
myFunction();
// std::cout << number << std::endl; // ❌ This would give an error, 'number' does not exist here
return 0;
}
Global Variables
Global variables are declared outside all functions and are accessible from any part of the program after their declaration. Their lifetime lasts the entire execution of the program.
#include <iostream>
int globalNumber = 20; // Global variable
void myFunction() {
std::cout << globalNumber << std::endl; // ✔️ You can use it here
}
int main() {
std::cout << globalNumber << std::endl; // ✔️ You can also use it here
myFunction();
return 0;
}
Instance Variables
Instance variables (also known as class data members). They are declared inside a class. Each instance of the class has its own copy of these variables.
#include <iostream>
class Person {
public:
std::string name; // Instance variable
void printName() {
std::cout << name << std::endl; // ✔️ You can use it here
}
};
int main() {
Person person;
person.name = "Luis"; // ✔️ This works
person.printName();
return 0;
}
Static Variables
Static variables are declared with the static keyword and belong to the class rather than a specific instance. They are accessible without creating an instance of the class and their lifetime lasts the entire execution of the program.
#include <iostream>
class Counter {
public:
static int globalCounter; // Static variable
void incrementCounter() {
globalCounter++; // ✔️ You can use it here
}
};
// Definition of the static variable outside of the class
int Counter::globalCounter = 0;
int main() {
Counter c1, c2;
c1.incrementCounter();
c2.incrementCounter();
std::cout << Counter::globalCounter << std::endl; // ✔️ This works, prints: 2
return 0;
}
