Language: EN

cpp-ambito-variables

What is the scope of variables in C++

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 within a function and are only accessible within that function. Their lifecycle begins when the function is called and ends when the function returns.

#include <iostream>

void myFunction() {
    int number = 10; // Local variable, exists only 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 of all functions and are accessible from anywhere in the program after their declaration. Their lifecycle lasts for 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 use it here as well
    
    myFunction();
    
    return 0;
}

Instance Variables

Instance variables (also known as data members of a class) are declared within 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 lifecycle lasts for 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 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;
}