#017 – Crash Course on Local Variables

Introduction

A local variable in C++ is any variable defined within a function (or block). This definition is type-agnostic—it does not matter whether the variable is a fundamental type (int, double), a standard library type (std::string, std::unique_ptr), or a user-defined type (class, struct). If it is declared inside a function, it is local.

void print_x()
{
    int x{10}; // local variable
    std::cout << x << '\\n';
}

void create_expenses() 
{
    std::array<double, 12> expenses {}; // local variable
}

struct Coordinate
{
    int x {};
    int y {};
};

void create_coordinate()
{
    Coordinate s{1, 11}; // local variable
}

// All variables are local, despite having completely different types.

Thus, despite being an introductory topic, local variables are used everywhere in a codebase. Additionally, where a variable is defined determines it’s scope and duration.

Local variables have local scope

Local variables have local scope, meaning:

  • They are only accessible within the block in which they are declared
  • They are do not exist outside that block
void example()
{
    int outer{100};

    {
        int inner{200};
        std::cout << outer << '\\n'; // Valid
        std::cout << inner << '\\n'; // Valid
    }

    std::cout << outer << '\\n'; // OK
    std::cout << inner << '\\n'; // ERROR: inner is out of scope
}

Local variables have local duration

Local variables exist for the duration of the function their defined in. In the example below, Logger is created when main() executes. The object goes out of scope when main() exits.

This is the foundation of important C++ idioms like RAII (Resource Acquisition Is Initialization).

#include <iostream>

struct Logger
{
    Logger()  { std::cout << "Constructed\\n"; }
    ~Logger() { std::cout << "Destroyed\\n"; }
};

int main()
{
    Logger log; // constructed here

} // destroyed here

// Output
Constructed
Destroyed

Ultimately

Local scope is used to restrict access of local variables, reducing their visibility to other parts of the program. This prevents accidental access to variables that shouldn’t be touched

Local duration means resources (memory, file handles, locks) are released automatically when a function returns, even if an exception is thrown.

Leave a Reply

Your email address will not be published. Required fields are marked *