SrcForge

Lesson 18

Scope of Variables

Covers local, global, block, and function scope, shadowing, and the scope resolution operator.

Lesson content

What is the scope of a variable in C++?

Scope defines the region of a program where a variable can be accessed.

  • Where a variable can be used
  • Where a variable cannot be accessed
  • Which parts of the program recognize the variable

Once a variable goes out of its scope, it is no longer accessible.

Why does variable scope exist?

  • Prevents accidental modification of variables
  • Improves code readability
  • Reduces naming conflicts
  • Makes debugging easier
  • Encourages modular programming

Real-world use cases

  • Functions
  • Loops
  • Conditional statements
  • Object-oriented programming
  • Large software projects
  • Game development
  • Embedded systems
  • Library development

Types of scope

Scope          | Accessible From
-------------- | -----------------------------------
Local Scope    | Current function only
Global Scope   | Entire program (after declaration)
Block Scope    | Current block {} only
Function Scope | Labels used with goto

Local scope

A local variable is declared inside a function and can only be accessed within that function.

void functionName()
{
    int number;
}
  • Exists only inside the function
  • Created when the function starts
  • Destroyed when the function ends
  • Cannot be accessed outside the function

Global scope

A global variable is declared outside all functions and can be accessed by any function that appears after its declaration.

int count = 0;

int main()
{
}
  • Exists throughout the program's execution
  • Accessible from multiple functions
  • Should be used carefully to avoid unintended side effects

Block scope

Variables declared inside a block enclosed by braces are block-scoped, including if, else, for, while, and switch.

if (true)
{
    int value = 10;
}

The variable value cannot be accessed outside the if block.

Variable shadowing

Variable shadowing occurs when a local variable has the same name as a global variable, hiding the global variable within its scope.

int number = 50;

int main()
{
    int number = 10;
}

Inside main(), the local variable is used instead of the global one.

Scope resolution operator (::)

The scope resolution operator lets you access a global variable when it is hidden by a local variable.

::number

Function scope

Labels used with the goto statement have function scope. Since goto is rarely used in modern C++, this is uncommon in everyday development.

Example 1: Local variable

#include <iostream>
using namespace std;

int main()
{
    int age = 20;

    cout << age;

    return 0;
}

Example 2: Global variable

#include <iostream>
using namespace std;

int count = 100;

void display()
{
    cout << count << '\n';
}

int main()
{
    display();

    cout << count;

    return 0;
}

Example 3: Block scope

#include <iostream>
using namespace std;

int main()
{
    if (true)
    {
        int marks = 95;

        cout << marks << '\n';
    }

    return 0;
}

Example 4: Variable shadowing

#include <iostream>
using namespace std;

int value = 100;

int main()
{
    int value = 50;

    cout << value << '\n';

    cout << ::value;

    return 0;
}

// Output:
// 50
// 100

Example 5: Variables inside a loop

#include <iostream>
using namespace std;

int main()
{
    for (int i = 1; i <= 3; i++)
    {
        cout << i << '\n';
    }

    // 'i' cannot be accessed here.

    return 0;
}

Common mistakes and pitfalls

  • Accessing a local variable outside its function. Fix: use it only within its scope
  • Using block variables outside the block. Fix: access them only within the block
  • Overusing global variables. Fix: pass values through function parameters
  • Shadowing global variables unintentionally. Fix: use different variable names
  • Assuming variables exist forever. Fix: understand their lifetime and scope
// Wrong
void display()
{
    int number = 25;
}

int main()
{
    cout << number;
}
// Correct
void display()
{
    int number = 25;

    cout << number;
}

Best practices

  • Keep variables in the smallest scope possible
  • Prefer local variables over global variables
  • Avoid unnecessary global state
  • Use descriptive variable names
  • Minimize variable shadowing
  • Pass data between functions using parameters instead of globals

When not to use this

  • Multiple functions modify the same variable
  • Building large applications where data ownership should be clear
  • Developing reusable libraries
  • Multi-threaded applications without proper synchronization

Summary

  • Scope determines where a variable can be accessed
  • Local variables exist only within their declaring function
  • Global variables are accessible throughout the program after declaration
  • Block-scoped variables exist only within their braces
  • Variable shadowing occurs when a local variable hides a global variable
  • The scope resolution operator (::) accesses a hidden global variable
  • Keep variable scope as small as possible

Frequently asked questions

What is variable scope in C++?

The region of a program where a variable can be accessed.

What is the difference between a local and a global variable?

A local variable is accessible only within its function or block, while a global variable is accessible throughout the program after declaration.

What is block scope?

A variable is accessible only within the braces it's declared in, such as an if statement or loop.

What is variable shadowing?

When a local variable shares a name with a global variable and hides it within its scope.

Why should I avoid using too many global variables?

Excessive globals make programs harder to understand, test, debug, and maintain.