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, 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 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 also use it here
    
    myFunction();
    
    return 0;
}

Instance variables

Instance variables (also known as data members of a class). They 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 to 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 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;
}